gpt4 book ai didi

closures - YII2 中的多个 where 子句

转载 作者:行者123 更新时间:2023-12-05 00:22:16 26 4
gpt4 key购买 nike

我有一个问题,如何在带有条件 WHERE 的 YII2 中使用闭包类型事件记录查询。

这是我想要达到的目标:

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);
}

如果有人知道这一点,请帮助。1

最佳答案

无法弄清楚这里的 Closure 是什么。
您可以使用 andFilterWhere()company_id条件,但您应该将其设置为默认值,因此如果 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

关于closures - YII2 中的多个 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com