[关闭]
@52fhy 2016-04-28T11:51:01.000000Z 字数 15447 阅读 504

Yii 框架学习--01 框架入门

PHP


Yii 是一个高性能的,适用于开发 WEB2.0 应用的 PHP 框架。

Yii目前有两个主要的版本: 2.0 和 1.1。本文以YII 2.0.7为例。

环境需求

Yii2.0 框架有一些系统上的需求:

PHP 版本 >= 5.4
Mcrypt PHP 扩展
OpenSSL PHP 扩展
Mbstring PHP 扩展

特点

安装

Yii可以通过Composer或者压缩包安装。

使用Composer安装

与安装Laravel框架类似,很多人会卡在这一步。要么是不会Composer,要么就是无法使用Composer安装。

如果还不知道Composer,先去学习了解了解:
http://www.cnblogs.com/52fhy/p/5246013.html

如果无法使用用Composer安装,很有可能是仓库访问不了,即被墙了。先更新Composer仓库源:

  1. # 修改 composer 的全局配置文件(推荐方式)
  2. # 打开命令行窗口(windows用户)或控制台(Linux、Mac 用户)并执行如下命令:
  3. composer config -g repo.packagist composer https://packagist.phpcomposer.com

接下来正式开始安装吧!
这里以YII 2.0 版本为例(PHP 版本 >= 5.4)。

  1. # 指定2.0.7版本,项目主目录是myyii2
  2. composer create-project yiisoft/yii2-app-basic yii2 2.0.7
  3. # 或者安装高级的应用程序模板:
  4. composer create-project yiisoft/yii2-app-advanced yii2adv 2.0.7

yii2的高级版和基本版的区别在哪里呢?
其实没太大区别。yii2-app-basic只有一个web应用,而yii2-app-advanced是默认带了前台和后台两个web应用,将两个应用整合在一个project里面,然后用common应用存放一些两个应用公共的一些东西。
https://www.zhihu.com/question/27916823

这里以安装yii2-app-basic为例。

等待安装(过程会比较长,期间还要github的token,建议还是下载一键安装包吧):

  1. Installing yiisoft/yii2-app-basic (2.0.7)
  2. - Installing yiisoft/yii2-app-basic (2.0.7)
  3. Downloading: 100%
  4. Created project in yii2
  5. Loading composer repositories with package information
  6. ...
  7. Token (hidden):
  8. Token stored successfully.
  9. - Installing yiisoft/yii2-composer (2.0.3)
  10. Downloading: 100%
  11. - Installing ezyang/htmlpurifier (v4.6.0)
  12. Downloading: 100%
  13. - Installing cebe/markdown (1.1.0)
  14. Downloading: 100%
  15. - Installing bower-asset/jquery (2.1.4)
  16. Downloading: 100%
  17. - Installing bower-asset/jquery.inputmask (3.1.63)
  18. Downloading: 100%
  19. - Installing bower-asset/punycode (v1.3.2)
  20. Downloading: 100%
  21. - Installing bower-asset/yii2-pjax (v2.0.4)
  22. Downloading: 100%
  23. - Installing yiisoft/yii2 (2.0.4)
  24. Downloading: 100%
  25. - Installing swiftmailer/swiftmailer (v5.4.1)
  26. Downloading: 100%
  27. - Installing yiisoft/yii2-swiftmailer (2.0.4)
  28. Downloading: 100%
  29. - Installing yiisoft/yii2-codeception (2.0.4)
  30. Downloading: 100%
  31. - Installing bower-asset/bootstrap (v3.3.5)
  32. Downloading: 100%
  33. - Installing yiisoft/yii2-bootstrap (2.0.4)
  34. Downloading: 100%
  35. - Installing yiisoft/yii2-debug (2.0.4)
  36. Downloading: 100%
  37. - Installing bower-asset/typeahead.js (v0.10.5)
  38. Downloading: 100%
  39. - Installing phpspec/php-diff (v1.0.2)
  40. Downloading: 100%
  41. - Installing yiisoft/yii2-gii (2.0.4)
  42. Downloading: 100%
  43. - Installing fzaninotto/faker (v1.5.0)
  44. Downloading: 100%
  45. - Installing yiisoft/yii2-faker (2.0.3)
  46. Downloading: 100%
  47. fzaninotto/faker suggests installing ext-intl (*)
  48. Writing lock file
  49. Generating autoload files
  50. chmod('runtime', 0777)...done.
  51. chmod('web/assets', 0777)...done.
  52. chmod('yii', 0755)...done.
  53. ...

安装过程中注意的:

  1. 1、提前安装好Composer
  2. 2、安装插件:php composer.phar global require "fxp/composer-asset-plugin:1.0.0"
  3. 3、通过命令行开始安装:
  4. 这一步耗时比较长,因为它在下载yii2框架。需要github账号,若提示安装过程中输入你的GitHub的用户名和密码。那就输入它们并继续即可。
  5. 如果需要输入token,注册登录github之后,在setting->Personal access tokens这里生成一个token,然后输入就可以了。复制粘贴(隐藏的),确认。

创建成功会在指定的项目根目录,如yii2目录下生成web\文件夹,里面有入口文件index.php

安装完便可以访问了:

  1. http://localhost/yii2/web/index.php

显示:

  1. Congratulations!
  2. You have successfully created your Yii-powered application.

一键安装包下载

一键安装包是在 YII 源码的基础上安装了依赖库(也就是已经做过 composer install,已经有了 vendor 目录),对于刚接触 YII2 或者使用 Composer 受挫的用户能够提供快速上手实践 YII2 的捷径。

下载以下归档文件之一,然后将其解压缩到一个Web可访问的文件夹:

yii2-app-basic
https://github.com/yiisoft/yii2/releases/download/2.0.7/yii-basic-app-2.0.7.tgz

yii2-app-advanced
https://github.com/yiisoft/yii2/releases/download/2.0.7/yii-advanced-app-2.0.7.tgz

下载很慢的话直接去我的百度云下载:
http://pan.baidu.com/s/1gfEsVar

注意:
通过安装包安装的需要在配置文件config/web.php,给 cookieValidationKey 配置项输入你的密钥:

  1. 'request' => [
  2. // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
  3. 'cookieValidationKey' => 'test', //建议填github上的token,随便填也行,不能是空
  4. ],

cookieValidationKey的作用暂时不做详细讲解。

解压yii-basic-app-2.0.7.tgz到服务器www目录,并更名为yii2。修改config/web.php填写密钥,然后访问:

  1. http://localhost/yii2/web/index.php

提示:

  1. Congratulations!
  2. You have successfully created your Yii-powered application.

ok了!

下文均以yii-basic-app-2.0.7.tgz源码进行搭建demo讲解。

项目结构

yii-basic-app

  1. assets/ assets资源定义
  2. commands/ 包含控制台命令类
  3. HelloController.php
  4. config/ 应用配置
  5. db.php 数据库配置
  6. params.php 通用参数配置
  7. web.php web配置
  8. console.php cli配置
  9. controllers/ 控制器
  10. SiteController.php
  11. mail/ e-mails的视图文件
  12. models/ 模型
  13. User.php
  14. runtime/ 包含 Yii 在运行时生成的文件,例如日志和缓存文件
  15. tests/ contains various tests for the basic application
  16. vendor/ 包含已经安装的 Composer 包,包括 Yii 框架自身
  17. views/ 视图
  18. web/ 入口文件和静态资源
  19. assets/ 包含 Yii 发布的资源文件(javascript css
  20. index.php 应用入口文件
  21. composer.json Composer 配置文件, 描述包信息
  22. yii Yii 控制台命令执行脚本
  23. yii.bat Yii 控制台命令执行脚本(Windows)

关于yii-basic-app说明:
在浏览器底部可以看到一个工具栏。这是 Yii 提供的很有用的调试工具,可以记录并显示大量的调试信息,例如日志信息,响应状态,数据库查询等等。

Yii 实现了模型-视图-控制器 (MVC)设计模式,这点在上述目录结构中也得以体现。 models 目录包含了所有模型类,views 目录包含了所有视图脚本,controllers 目录包含了所有控制器类。

Yii 流程:
1. 用户向入口脚本 web/index.php 发起请求。
2. 入口脚本加载应用配置并创建一个应用实例去处理请求。
3. 应用通过请求组件解析请求的路由。
4. 应用创建一个控制器实例去处理请求。
5. 控制器创建一个操作实例并针对操作执行过滤器。
6. 如果任何一个过滤器返回失败,则操作退出。
7. 如果所有过滤器都通过,操作将被执行。
8. 操作会加载一个数据模型,或许是来自数据库。
9. 操作会渲染一个视图,把数据模型提供给它。
10. 渲染结果返回给响应组件。
11. 响应组件发送渲染结果给用户浏览器。

控制器(Controllers)

控制器路径:controllers。使用 app\controllers 命名空间。

示例:TestController.php

  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\web\Controller;
  5. class TestController extends Controller{
  6. /**
  7. * index
  8. * Yii 使用 action 前缀区分普通方法和操作。action 前缀后面的名称被映射为操作的 ID
  9. */
  10. public function actionIndex($msg = 'hello') {
  11. //index 视图应该存为 views/test/index.php 文件
  12. //按 views/控制器 ID/视图名.php 路径加载 PHP 文件
  13. return $this->render('index', array('msg' => $msg));
  14. }
  15. /**
  16. * my-index
  17. * 操作 ID 总是被以小写处理,如果一个操作 ID 由多个单词组成,单词之间将由连字符连接(如 my-index);
  18. * 操作 ID 映射为方法名时移除了连字符,将每个单词首字母大写,并加上 action 前缀。例子:操作 ID my-index 相当于方法名 actionMyIndex
  19. */
  20. public function actionMyIndex($msg = 'hello') {
  21. return $this->render('my-index', array('msg' => $msg));
  22. }
  23. }

创建对应的视图:
views/test/index.php
views/test/my-index.php

  1. <!DOCTYPE html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>test</title>
  5. </head>
  6. <body>
  7. <?php echo $msg;?>
  8. </body>

访问:

  1. http://localhost/yii2/web/index.php?r=test/index&msg=hello
  2. http://localhost/yii2/web/index.php?r=test/my-index&msg=welcome

生成url

  1. Yii::$app->urlManager->createUrl('index/test');

结果:/yii2/web/index.php?r=index%2Ftest

  1. \yii\helpers\Url::to(array('index/test'));

结果:/yii2/web/index.php?r=index%2Ftest

路由(Route)

YII 路由与大多数框架如ThinkPHP、CI类似,是自动化的,不需要单独去配置。这点与Laravel不同。

URL 中的参数 r 代表路由。路由格式是 控制器 ID/操作 ID

示例:

  1. http://localhost/yii2/web/index.php?r=test/index&msg=hello

代表TestController/actionIndex,其中方法actionIndex接收了一个参数,键名是msg,键值是hello

实际上我们使用$_GET也可以获取URL上的所有参数,包括路由r

配置

入口文件配置

  1. //开启debug,应用会保留更多日志信息,如果抛出异常,会显示详细的错误调用堆栈
  2. defined('YII_DEBUG') or define('YII_DEBUG', true);
  3. //环境定义
  4. defined('YII_ENV') or define('YII_ENV', 'dev'); //dev,prod

全局配置

包含:
db.php 数据库配置
params.php 通用参数配置
web.php web配置
console.php cli配置

详见下章:http://www.cnblogs.com/52fhy/p/5349394.html

模型(Model)

Yii2 模型文件都放在 models 目录下,以及默认使用 app\models 命名空间。

Yii 里模型的类名文件名是一模一样的。例如UserAddress.php对应类UserAddress。建议使用驼峰命名。

示例:models/EntryForm.php

  1. <?php
  2. namespace app\models;
  3. use yii\base\Model;
  4. class EntryForm extends Model
  5. {
  6. public $name;
  7. public $email;
  8. /**
  9. * 返回数据验证规则的集合
  10. */
  11. public function rules()
  12. {
  13. return [
  14. //name 和 email 值都是必须的
  15. [['name', 'email'], 'required'],
  16. //email 的值必须满足email规则验证
  17. ['email', 'email'],
  18. ];
  19. }
  20. }

注意:yii\base\Model 被用于普通模型类的父类并但与数据表无关。真正与数据的CURD相关的是yii\db\ActiveRecord,继承自 yii\base\Model,增加了数据库处理。

上面的示例中验证规则(rules)可以在控制器使用 yii\base\Model::validate() 方法触发数据验证。

如何在Controller里使用Model?

需要引入命名空间并实例化模型:

  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\web\Controller;
  5. use app\models\EntryForm;//引入命名空间
  6. class TestController extends Controller{
  7. public function actionIndex($msg = 'hello') {
  8. $model = new EntryForm();
  9. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  10. return $this->render('index', array('msg' => $msg));
  11. }
  12. }
  13. }

表达式 Yii::$app 代表应用实例,它是一个全局可访问的单例。同时它也是一个服务定位器,能提供 request,response,db 等等特定功能的组件。在上面的代码里就是使用 request 组件来访问应用实例收到的 $_POST 数据。

视图(views)

视图根路径:views

视图与控制器对应关系:
views/控制器 ID/视图名.php 路径加载 PHP 文件

以上面的TestController为例,有:

  1. $this->render('index', array('msg' => $msg));
  2. $this->render('my-index', array('msg' => $msg));

分别对应:

  1. views/test/index.php
  2. views/test/my-index.php

即控制器/方法与视图目录是一一对应的。

视图内容其实就是html代码。为了防止跨站脚本(XSS)攻击,我们可以在视图中使用yii\helpers\Html::encode()进行处理:

views/test/index.php

  1. <!DOCTYPE html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>test</title>
  5. </head>
  6. <body>
  7. <?php use yii\helpers\Html; ?>
  8. <?= Html::encode($msg) ?>
  9. </body>

视图可以有子目录:

  1. $this->render('sub/index', array('msg' => $msg));

对应:

  1. views/test/sub/index.php

传递数据到视图

  1. $this->render('index', array('msg' => $msg));

数据库操作

数据库配置

数据库相关配置文件都在 config/db.php:

  1. <?php
  2. return [
  3. 'class' => 'yii\db\Connection',
  4. 'dsn' => 'mysql:host=localhost;dbname=yii2basic',
  5. 'username' => 'root',
  6. 'password' => '',
  7. 'charset' => 'utf8',
  8. ];

上面配置的数据库连接可以在应用中通过 Yii::$app->db 表达式访问。

为了方便下文继续演示,这里新建一个数据库yii2basic,并新建表country:

  1. CREATE TABLE `country` (
  2. `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  3. `code` CHAR(2) NOT NULL ,
  4. `name` CHAR(52) NOT NULL,
  5. `population` INT(11) NOT NULL DEFAULT '0'
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  7. INSERT INTO `country` VALUES (null, 'AU','Australia',18886000);
  8. INSERT INTO `country` VALUES (null, 'CA','Canada',1147000);
  9. INSERT INTO `country` VALUES (null, 'CN','China',1277558000);
  10. INSERT INTO `country` VALUES (null, 'US','United States',278357000);

使用模型操作数据

为了使用ActiveRecord里面的方法,这里不再继承\yii\base\Model,而是继承\yii\db\ActiveRecord

这里建立一个模型Country

  1. <?php
  2. namespace app\models;
  3. use yii\db\ActiveRecord;
  4. class Country extends ActiveRecord{
  5. }

在里面写任何代码。只需要像现在这样,Yii就能根据类名去猜测对应的数据表名。如果类名和数据表名不能直接对应,可以覆写yii\db\ActiveRecord::tableName() 方法去显式指定相关表名:

  1. public static function tableName() {
  2. return 'country';
  3. }

控制器里使用模型:
首先引入命名空间:

  1. use app\models\Country;

然后直接使用模型里的数据库操作方法:

  1. public function actionListCountry() {
  2. //获取所有
  3. $list = Country::find()->orderBy('name')->all();
  4. //获取一条
  5. $one = Country::findOne('US');
  6. print_r($one->name);
  7. //更新
  8. / 修改 name U.S.A. 并在数据库中保存更改
  9. $one->name = 'U.S.A.';
  10. $one->save();
  11. }

Active Record

\yii\db\ActiveQuery继承自\yii\db\Query

通过\yii\db\ActiveRecord::find()可获取\yii\db\ActiveQuery实例。

下面以Customer模型及customer作为演示。

新增(create)

  1. yii\db\ActiveRecord::save()
  2. yii\db\ActiveRecord::insert()

示例:

  1. $customer = new Customer();
  2. $customer->name = 'Qiang';
  3. $customer->save(); // 等同于 $customer->insert();

删除(delete)

  1. yii\db\ActiveRecord::delete()
  2. //静态方法,作用于整张表
  3. yii\db\ActiveRecord::deleteAll()

示例:

  1. // 删除已有客户记录
  2. $customer = Customer::findOne($id);
  3. $customer->delete();
  4. // 删除多个年龄大于20,性别为男(Male)的客户记录
  5. Customer::deleteAll('age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']);

更新(update)

  1. yii\db\ActiveRecord::save()
  2. yii\db\ActiveRecord::update()
  3. //静态方法,作用于整张表
  4. yii\db\ActiveRecord::updateCounters()
  5. yii\db\ActiveRecord::updateAll()
  6. yii\db\ActiveRecord::updateAllCounters()

示例:

  1. $customer = Country::findOne('Li');
  2. $customer->name = 'Qiang';
  3. $customer->save(); // 等同于 $customer->update();
  4. // 所有客户的age(年龄)字段加1:
  5. Customer::updateAllCounters(['age' => 1]);

查询(read)

  1. yii\db\ActiveRecord::find() //返回ActiveRecord对象
  2. yii\db\ActiveRecord::findBySql() //通过SQL查询返回ActiveRecord对象
  3. // 两个快捷方法:直接返回一个或者一组结果
  4. yii\db\ActiveRecord::findOne() //返回第一个匹配到的实例
  5. yii\db\ActiveRecord::findAll() //返回所有

find()返回一个ActiveRecord对象,需要使用one()或者all()获取最终数据。
findBySql()接收SQL,返回一个ActiveRecord对象,需要使用one()或者all()获取最终数据。

findOne()和findAll()直接返回对象数组,不需要再使用one()或者all()。

都支持静态方法或者直接调用。

示例:

  1. /**find**/
  2. $m = new Country();
  3. $m->find()->all();//返回对象
  4. $m->find()->one();//返回对象,仅返回一条记录
  5. $m->find()->asArray()->all();//asArray()返回数组
  6. $m->find()->select('name')->column(); //返回指定字段的数组集合
  7. $m->find()->column();//返回第一个字段的数组集合
  8. $m->find()->where(['name'=> 'China'] )->one();
  9. $m->find()->where(['name'=> 'China'] )->all();
  10. $m->find()->where(['name' => 'China', 'code' => 'CN'] )->all();
  11. $m->find()->where(['name'=> 'China'] )->offset(1)->limit(1)->all();
  12. $m->find()->orderBy('id DESC')->all();
  13. $m->find()->where(['name'=> 'China'] )->orderBy('code desc')->limit(2)->all();
  14. //andWhere与where是一样的,多个建议使用andWhere、orWhere
  15. $m->find()->where(['id' => 1])->count();
  16. $m->find()->where(['id' => 1])->andWhere(['code' => 'CN'])->count();
  17. $m->find()->where(['id' => 1])->orWhere(['code' => 'CN'])->count();
  18. //findBySql
  19. $m->findBySql('select * from country')->one();
  20. $m->findBySql('select * from country')->all();
  21. /* where高级用法:当参数大于2个时且无键值对,第一个表示操作符
  22. * [操作符, 操作数1, 操作数2, ...]
  23. */
  24. //比较:>,<,=,>=,<=
  25. $m->find()->where(['=', 'id', '3'])->all(); //id=3
  26. $m->find()->where(['>', 'id', '3'])->all(); //id>=3
  27. //逻辑:and,or
  28. $m->find()->where(['and', 'id=5', ['code' => 'CN']])->all();//即 id=5 AND code ='CN';字符型操作数需要用数组表示
  29. $m->find()->where(['or', 'id=5', 'id=1'])->all();
  30. //between,not between
  31. $m->find()->where(['between', 'id', 1, 3])->all(); //id between 1 AND 3
  32. //in,not in
  33. $m->find()->where(['in', 'id', [1,2,3]])->all(); //id in (1,2,3)
  34. //like,or like, not like,or not like 不支持左右like
  35. $m->find()->where(['like', 'name', 'A'])->all();
  36. $m->find()->where(['like', 'name', ['A','B']])->all();
  37. //exists,not exists
  38. //其它
  39. $m->find()->scalar(); //此方法返回值的第一行第一列的值
  40. $m->find()->count(); //此方法返回记录的数量
  41. $m->find()->average(); //此方法返回指定列的平均值
  42. $m->find()->min(); //此方法返回指定列的最小值
  43. $m->find()->max(); //此方法返回指定列的最大值
  44. $m->find()->exists();//此方法返回一个bool值指示是否可以查询数据
  45. //返回数组以 ID 为索引
  46. $m->find()->indexBy('id')->all();
  47. //distinct() 方法来去除重复行
  48. $m->find()->select('name')->distinct()->all(); //SELECT DISTINCT `name` FROM `country`
  49. //groupBy,having
  50. //SELECT `name`, count(*) as sum FROM `country` GROUP BY `name`
  51. $m->find()
  52. ->select(['name','count(*) as sum'])
  53. ->groupBy('name')
  54. ->all();
  55. //SELECT `name`, count(*) as sum FROM `country` GROUP BY `name` HAVING `sum` >= 2
  56. $m->find()
  57. ->select(['name','count(*) as sum'])
  58. ->groupBy('name')
  59. ->having(['>=','sum', 2])
  60. ->all();
  61. //多表关联建议使用SQL
  62. // yii\db\Query::join($type, $table, $on, $params) 类型(join,left,right),需要join的表,连接条件,可选参数
  63. $m->find()->join('inner','articles', 'country.id = articles.id')->all();
  64. $m->find()->innerJoin('articles', 'country.id = articles.id')->all();
  65. //SELECT * FROM `country` INNER JOIN `articles` ON country.id = articles.id
  66. /**findOne(),findAll()**/
  67. Country::findOne(1); // 返回 id 为 1 的数据
  68. Country::findOne([
  69. 'id' => 1,
  70. 'status' => 1,
  71. ]);
  72. Country::findAll([1, 2, 3]); // 返回id为1、2、3的一组数据
  73. Country::findAll(['status' => 1,]);
  74. /**批量获取**/
  75. // 一次提取 10 个客户信息
  76. foreach ($m->find()->batch(10) as $customers) {
  77. // $customers 是 10 个或更少的客户对象的数组
  78. }
  79. // 一次提取 10 个客户并一个一个地遍历处理
  80. foreach ($m->find()->each(10) as $customer) {
  81. // $customer 是一个 ”Customer“ 对象
  82. }
  83. // 贪婪加载模式的批处理查询
  84. foreach ($m->find()->with('orders')->each() as $customer) {
  85. }

注意:
调用 save()insert()update() 这三个方法时,会自动调用yii\base\Model::validate()方法。如果验证失败,数据将不会保存进数据库。

更多查看:http://www.yiichina.com/doc/guide/2.0/db-active-record

使用Query查询

由于ActiveRecord是通过\yii\db\ActiveRecord::find()获取的\yii\db\ActiveQuery实例,而\yii\db\ActiveQuery继承自\yii\db\Query,那么其实可以直接使用\yii\db\Query里的方法进行查询数据。

此时,除了ActiveRecord里的find()insert()update()updateAlldelete()deleteAll()findBySql()asArray()等不能使用外,其它的都是可以用的,例如where()allonelimit等等。

可以这么说,对于ActiveRecord里示例里的查询方法,只要把find()替换成from($table)就可以用了。Query默认返回的数组,不是对象。下面是例子:

  1. $m = new \yii\db\Query();
  2. $table = 'country';
  3. $m->from($table)->all();//返回数组
  4. $m->from($table)->one();//返回数组,仅返回一条记录
  5. $m->from($table)->select('name')->column(); //返回指定字段的数组集合
  6. $m->from($table)->column();//返回第一个字段的数组集合
  7. $m->from($table)->where(['name'=> 'China'] )->one();
  8. $m->from($table)->where(['name'=> 'China'] )->all();
  9. $m->from($table)->where(['name' => 'China', 'code' => 'CN'] )->all();
  10. $m->from($table)->where(['name'=> 'China'] )->offset(1)->limit(1)->all();
  11. $m->from($table)->orderBy('id DESC')->all();
  12. $m->from($table)->where(['name'=> 'China'] )->orderBy('code desc')->limit(2)->all();
  13. //andWhere与where是一样的,多个建议使用andWhere、orWhere
  14. $m->from($table)->where(['id' => 1])->count();
  15. $m->from($table)->where(['id' => 1])->andWhere(['code' => 'CN'])->count();
  16. $m->from($table)->where(['id' => 1])->orWhere(['code' => 'CN'])->count();

http://www.yiichina.com/doc/guide/2.0/db-query-builder

事务

在Yii中,使用 yii\db\Transaction 来表示数据库事务。

一般情况下,我们从数据库连接启用事务,通常采用如下的形式:

  1. $connection = \Yii::$app->db;
  2. $transaction = $connection->beginTransaction();
  3. try {
  4. $connection->createCommand($sql1)->execute();
  5. $connection->createCommand($sql2)->execute();
  6. // ... 执行其他 SQL 语句 ...
  7. $transaction->commit();
  8. } catch(Exception $e) {
  9. $transaction->rollBack();
  10. }

示例:

  1. $dbTrans= Yii::app()->db->beginTransaction();
  2. try{
  3. $customer = new Customer();
  4. $customer->name = 'Qiang';
  5. if(!$customer->save()) throw newException("Error Processing Request", 1);
  6. $dbTrans->commit();
  7. // $this->_end(0,'添加成功!!!');
  8. }catch(Exception$e){
  9. $dbTrans->rollback();
  10. // $this->_end($e->getCode(),$e->getMessage());

深入理解:
http://www.yiichina.com/doc/guide/2.0/db-dao
http://www.digpage.com/transaction.html
http://blog.csdn.net/xundh/article/details/45955195/

学习资料

Yii 2.0 权威指南 - 文档 - Yii Framework 中文社区
http://www.yiichina.com/doc/guide/2.0

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注