我有一个问题,如何使用条件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);
}
如果有人知道这一点,请提供帮助。
答案 0 :(得分:5)
无法弄清楚Closure的用途。
您可以将andFilterWhere()
用于company_id
条件,但是您应该将其设置为默认值为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
}
http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#andFilterWhere()-detail
答案 1 :(得分:1)
public function getUsers($limit = 10, $type = 1, $company_id = null)
{
$query =User::find()
->where(['type' => $type])
->orderBy([ 'created_at'=> SORT_DESC ])
->limit($limit)
->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// then filter data
if($company_id != null)
$query->andFilterWhere(['company_id' => $company_id]);
}
答案 2 :(得分:0)
我在Laravel MVC中遇到了同样的问题,这样的事情对我来说还不错。
替换
$query->andWhere(['company_id' => $company_id]);
带
$query->where(['company_id' => $company_id]);