我有一个数组
//dynamically generated. dynamic number of elements
$keywords = ['google', 'youlense'];
对于完全匹配的$keywork
映射到内容列中的行的值,我可以执行以下操作:
$result = \App\Table::where(function($query){
$query->whereIn('content', $keywords);
});
,结果有点
select * from tables where content IN ('google', 'youlense');
但我想使用LIKE
运算符,结果可能就像
select * from tables where content LIKE ('%google%', '%youlense%');
我知道mysql中不允许这样做,但有些人可以推荐一种简单而干净的技术来处理这个
答案 0 :(得分:4)
您只需对每个关键字使用orWhere
方法,它就等同于whereIn
。代码如下:
$result = \App\Table::where(function($query){
$query->orWhere('content', 'LIKE', '%google%')
->orWhere('content', 'LIKE', '%youlense%')
-> and so on;
});
$result = \App\Table::where(function($query) use($keywords){
foreach($keywords as $keyword) {
$query->orWhere('content', 'LIKE', "%$keywords%")
}
});
注意:获取查询可能会非常缓慢。
答案 1 :(得分:1)
您可以编写一个基本上可以执行以下操作的函数:
public function searchByKeywords(array $keywords = array()){
$result = \App\Table::where(function($query) use ($keywords){
foreach($keywords as $keyword){
$query = $query->orWhere('content', 'LIKE', "%$keyword%");
}
return $query;
});
return $result->get(); // at this line the query will be executed only
// after it was built in the last few lines
}