控制器
控制器周期
beforeAction
/**
* action 运行的前置操作
*
* 比较适合统一化的数据验证,请求数据的接受等
* @param \yii\base\Action $action action 类
* @return bool 返回ture 控制器周期才会走下去
*/
public function beforeAction($action)
{
var_dump($action->id, $action->controller->id);
return parent::beforeAction($action); // TODO: Change the autogenerated stub
}
afterAction
/**
* action 后置操作
*
* 比较适合返回最后的日志搜集
* @param \yii\base\Action $action action 类
* @param mixed $result
* @return mixed
*/
public function afterAction($action, $result)
{
return parent::afterAction($action, $result); // TODO: Change the autogenerated stub
}
模型
AR 模型 常用方法
查询数据
// 查询单条
$one = Post::find()->where(['id' => 1])->one();
// 或者
$one = Post::finOne(1);
// 查询多条
$posts = Post::find()->where(['status' => 1])->all();
// 或者
$posts = Post::findAll(['status' => 1]);
// 通过sql查询
$posts = Post::findBySql('SELECT * FROM `posts` WHERE `status` = :status', [':status' => 1])->all();
查询条件的设定
where 查询支持的参数
- 字符串格式 例如: ‘status=1’
// 对应的SQL: WHERE status = 1
$query->where('status = 1');
// 使用字符串方式,可以绑定参数
$query->where('status = :status', [':status' => 1])
- 哈希格式 例如: [‘status’ => 1, ‘type’ => 1]
哈希格式最适合用来指定多个 AND 串联起来的简单的”等于断言”子条件。
// 对应的SQL: WHERE (`status`=1) AND (`type`=1)
$query->where(['status' => 1, 'type' => 1])
// 如果值为一个数组会转为IN 对应SQL: WHERE (`status`=1) AND (`type` IN (1, 2, 3))
$query->where(['status' => 1, 'type' => [1, 2, 3]])
- 操作符格式 例如: [‘=’, ‘status’, 1]
可以实现比较复杂的查询条件
- 格式
['操作符', 操作数1, 操作数2, ...];
- 演示
// 简单单个查询 对应的SQL: WHERE `status` >= 1
$query->where(['>=', 'status', 1])
// 多个条件 AND 连接 对应的SQL: WHERE (`status` >= 1) AND (`type` <= 3)
$query->where(['and', ['>=', 'status', 1], ['<=', 'type', 3]])
// 多个条件 OR 连接 对应SQL: WHERE (`status` IN (1, 3)) OR (`type` >= 2)
$query->where('or', ['in', 'status', [1, 3], ['>=', 'type', 2]])
// 比较复杂组合的SQL 对应SQL: WHERE (`create_type` = 6) AND (`status` = 0) AND (`is_fail` = 0) AND (((`last_view_time` = 0) AND (`create_time` <= 1503562511)) OR ((`last_view_time` > 0) AND (`last_view_time` <= 1503562511)))
$query->where([
'and',
['=', 'create_type', 6],
['=', 'status', 0],
['=', 'is_fail', 0],
['or',
['and', ['=', 'last_view_time', 0], ['<=', 'create_time', time()]],
['and', ['>', 'last_view_time', 0], ['<=', 'last_view_time', time()]]
]
]);
操作符说明
- and 和 or 确定多个条件通过什么方式连接
between 和 not between
// 数组需要四个元素 对应SQL: WHERE `id` BETWEEN 1 AND 10 ['between', 'id', 1, 10]
in 和 not in
// 对应SQL: WHERE `status` IN (1, 3) ['in', 'status', [1, 3]]
like
// 默认 对应SQL: WHERE `name` LIKE '%username%' ['like', 'name', 'usernam