例如,我们现在有这样的SQL:
SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)
看起来并没有那么复杂,是的,我们在Yii2里可以这样写:
arname()->find()
->where("user_id IN(1,5,8) AND (status = 1 OR verified = 1) OR (social_account = 1 AND enable_social = 1)")
->all();
但这样的话,如果涉及到(1,5,8)是变量,就得产生很多的SQL拼接,也失去了使用ActiveRecord的意义了。
所以,进一步的时候,你可以这样写:
$query = arname()->find()
->where(['and',[user_id'=>[1,5,8]],['or','status=1','verified=1']])
->orWhere(['social_account'=>1,'enable_social'=>1]);
上述的已经有很好的雏形了,所以,我们再次改成
$model = arname()->find()
->andWhere(['user_id'=>[1,5,8]])
->andWhere(['or',
['status'=>1], //这里即使是变量也不影响
['verified'=>1]
])
->orWhere(['and',
['social_account'=>1],
['enable_social'=>1]
])
->all();
清晰明了。