我有一个问题,如何使用条件WHERE在YII2中使用Closure类型Active记录查询.
这就是我想要实现的目标:
public function getUsers($limit = 10, $type = 1, $company_id = 0) {
return User::find()->where( function($query) use ($type, $company_id){
$query->where(['type' => $type]);
if($company_id != 0) {
$query->andWhere(['company_id' => $company_id]);
}
})
->orderBy([ 'created_at'=> SORT_DESC, ])
->limit($limit);
}
Run Code Online (Sandbox Code Playgroud)
如果有人知道这个,请帮忙
无法弄清楚Closure的用途.您可以使用andFilterWhere()for company_idcondition,但是您应该将其设置为null作为默认值,因此如果未初始化company_id,则将忽略此条件:
public function getUsers($limit = 10, $type = 1, $company_id = null) {
return User::find()
->where(['type' => $type])
->andFilterWhere(['company_id' => $company_id])
->orderBy([ 'created_at'=> SORT_DESC ])
->limit($limit)
->all(); //probably you muiss it
}
Run Code Online (Sandbox Code Playgroud)
http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#andFilterWhere()-detail
| 归档时间: |
|
| 查看次数: |
3529 次 |
| 最近记录: |