像运算符,右侧匹配yii2中arraylist中的%

时间:2018-12-01 11:49:13

标签: php yii yii2

这是一个数组和yii查询生成器

$arr = ['delhi','mumbai'];
$query->orWhere(['LIKE','city',$arr."%",false]);

我想生成这样的条件

where city like 'delhi%' or city like 'mumbai%'

2 个答案:

答案 0 :(得分:1)

参考源代码:\yii\db\QueryBuilder::buildLikeCondition()

$cities = ['city1', 'city2', 'city3'];
$query = new \yii\db\Query();

$query->where(['or like', 'city', array_map(function ($item) {
    return $item.'%';
}, $cities), false]); 

print_r($query->createCommand()->rawSql);

// output: SELECT * WHERE `city` LIKE 'city1%' OR `city` LIKE 'city2%' OR `city` LIKE 'city3%'

答案 1 :(得分:-1)

只需使用SIMILAR TO in PostgresREGEXP_LIKE in MySQL(取决于您的数据库引擎)代替LIKE

例如,您的查询应如下所示:

$query->andWhere(['SIMILAR TO', 'city','('.implode('|', $arr).')%',false]);