我有一项任务 - 添加搜索模型按全名搜索。 全名是名字+姓氏。所以我需要构建像
这样的查询WHERE first_name LIKE '%var%' OR last_name LIKE '%var%'
我能做到的唯一方法:
$query->andFilterWhere([
'OR',
'profiles.first_name LIKE "%' . $this->userFullName . '%" ',
'profiles.last_name LIKE "%' . $this->userFullName . '%"'
]);
但我不喜欢它因为它不安全。 我不知道怎么样...... 我认为有一种方法可以使用yii2活动构建器构建此类查询,并且我希望得到结果类似于
$query->andFilterWhere(['LIKE', 'profiles.first_name', $this->userFullName]);
$query->andFilterWhere(['OR LIKE', 'profiles.last_name', $this->userFullName]);
问题在于查询喜欢,我可以使用数组作为属性将被comapred的值,但我不能使用数组作为要比较的属性列表。
或
$subQuery1 = Profile::find()->Where(['LIKE', 'profiles.first_name', $this->userFullName]);
$subQuery2 = Profile::find()->Where(['LIKE', 'profiles.last_name', $this->userFullName]);
//i think its overloaded(3 queries insteadof 1 but still) and the final query
$query->andFilterWhere([
'OR',
$subQuery1,
$subQuery2
]);
有关如何构建查询的任何想法"%"?
答案 0 :(得分:45)
你应该试试:
$query->andFilterWhere([
'or',
['like', 'profiles.first_name', $this->userFullName],
['like', 'profiles.last_name', $this->userFullName],
]);
or
:类似于and
运算符,但操作数是使用OR
连接的。例如,['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]
将生成(type IN (7, 8, 9) OR (id IN (1, 2, 3)))
。
了解详情:http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail