Yii2 ActiveQuery 'OR LIKE' 过滤器

标签 yii2 query-builder

我有一个任务 - 添加到按全名搜索的搜索模型。 全名是名字+姓氏。所以我需要构建像

这样的查询
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]);

问题出在查询中,例如,我可以使用数组作为要比较属性的值,但不能使用数组作为要比较的属性列表。

$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 instead of 1 but still) and the final query
$query->andFilterWhere([
    'OR',
    $subQuery1,
    $subQuery2
]);

关于如何构建不带“%”的查询有什么想法吗?

最佳答案

你应该简单地尝试:

$query->andFilterWhere([
    'or',
    ['like', 'profiles.first_name', $this->userFullName],
    ['like', 'profiles.last_name', $this->userFullName],
]);

or: similar to the and operator except that the operands are concatenated using OR. For example, ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]] will generate (type IN (7, 8, 9) OR (id IN (1, 2, 3))).

了解更多:http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail

关于Yii2 ActiveQuery 'OR LIKE' 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28592805/

相关文章:

php - 如何使用 QueryBuilder 计算 CURRENT_DATE() 与上个月之间的天数差异?

php - CodeIgniter 查询生成器类嵌套查询

sql - 数组字段包含元素的 Doctrine

javascript - Ajax 调用中未找到 Yii2 类

javascript - Yii2:来自 PHP 的 window.open

gridview - 在 Gridview yii2 中搜索

file-upload - 文件不在 yii2 中上传

php - 使用 Yii2 将 Android 表情符号从 Firebase 保存到 MySQL

sql - 从不同的 Controller 插入 yii2

php - laravel 搜索以空格分隔的多个单词