如何在Yii ActiveRecord中编写OR表达式?
I tried the following, but it didn't work.
$kw = \app\models\Keyword::find()->where(['keyword'=>$word, ['or', ['country' => $country], ['country' => null]], ['or', ['language' => $language], ['language' => null]]]);
I also tried
$kw = \app\models\Keyword::find()->where(['keyword'=>$word, ['or', 'country' => $country, 'country' => null], ['or', 'language' => $language, 'language' => null]]);
Worthless error:
PHP Warning 'yii\base\ErrorException' with message 'strtoupper() expects parameter 1 to be string, array given'
Docs: http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail
I solved it with andWhere()
$kw = \app\models\Keyword::find()->where(['keyword'=>$word])->andWhere(['or', ['country' => $country], ['country' => null]])->andWhere(['or', ['language' => $language], ['language' => null]]);
which yields
SELECT * FROM `keyword` WHERE ((`keyword`='women\'s running shoes') AND ((`country`='US') OR (`country` IS NULL))) AND ((`language`='en') OR (`language` IS NULL)) ORDER BY `country`, `language`
You can use orWhere()
to do it:
$kw = \app\models\Keyword::find()->where(['keyword'=>$word])->orWhere(['country' => $country])->orWhere(['language' => $language]);
See this for more detail
www.yiiframework.com/doc-2.0/yii-db-querytrait.html#orWhere()-detaila
Try using Keyword::find()
instead of \app\models\Keyword::find()
I had the similar problem. It worked fine for me. Hope it works for you too.