我需要使用方法(在哪里)查询我的模型并使用LIKE查找结果;
我的代码:
public function scopeTags($query, $tags)
{
/*
* random = [ 'tag1', 'tag2', 'tag3', ...]
*/
$random = $tags[rand(0, count($tags) - 1)];
return $query->where('tags', 'LIKE', "%{$random}%");
}
我需要这样的东西:
public function scopeTags($query, $tags)
{
/*
* random = [ 'tag1', 'tag2', 'tag3', ...]
*/
foreach($tags as $tag) {
$random[] = "%{$tag}%";
}
return $query->where('tags', 'LIKE', $random);
}
最好的方法是什么?
答案 0 :(得分:1)
您需要为每个标记添加额外的where
函数调用:
public function scopeTags($query, $tags)
{
/*
* random = [ 'tag1', 'tag2', 'tag3', ...]
*/
foreach($tags as $tag) {
$query->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND
//$query->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR
}
return $query;
}
或者如果您需要用括号模拟WHERE (tags like '%tag1%' AND tags like'%tag2%' AND ...) AND (something else)
:
public function scopeTags($query, $tags)
{
return $query->where(function($q) use($tags) {
foreach($tags as $tag) {
$q->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND
//$q->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR
}
return $q;
});
}