小编Col*_*Nik的帖子

yii2 ActiveQuery'OR LIKE'过滤器

我有一个任务 - 添加搜索模型搜索全名.全名是名字+姓氏.所以我需要构建查询

WHERE first_name LIKE '%var%' OR last_name LIKE '%var%'
Run Code Online (Sandbox Code Playgroud)

我能做到的唯一方法:

$query->andFilterWhere([
'OR',
'profiles.first_name LIKE "%' . $this->userFullName . '%" ',
'profiles.last_name LIKE "%' . $this->userFullName . '%"'
]);
Run Code Online (Sandbox Code Playgroud)

但我不喜欢它,因为它不安全.我不知道怎么...我认为有办法用yii2活动构建器构建这样的查询,我想得到结果像

$query->andFilterWhere(['LIKE', 'profiles.first_name', $this->userFullName]);
$query->andFilterWhere(['OR LIKE', 'profiles.last_name', $this->userFullName]);
Run Code Online (Sandbox Code Playgroud)

问题出在查询中,我可以使用数组作为属性将被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
]);
Run Code Online (Sandbox Code Playgroud)

任何想法如何构建查询whithout"%"?

query-builder yii2

22
推荐指数
1
解决办法
5万
查看次数

标签 统计

query-builder ×1

yii2 ×1