Search Laravel搜索标题和相关标签
我想按标题和相关标签搜索帖子,它们与帖子有多对多的关系。我走了很远,但有件事困扰着我。这是我的密码:Search Laravel搜索标题和相关标签,search,laravel,tags,many-to-many,eloquent,Search,Laravel,Tags,Many To Many,Eloquent,我想按标题和相关标签搜索帖子,它们与帖子有多对多的关系。我走了很远,但有件事困扰着我。这是我的密码: $searchInput = Input::get('search'); $posts = Post::join('post_tag', 'post_tag.post_id','=','post.id') ->join('tag','tag.id','=','post_tag.tag_id') ->where('post.titl
$searchInput = Input::get('search');
$posts = Post::join('post_tag', 'post_tag.post_id','=','post.id')
->join('tag','tag.id','=','post_tag.tag_id')
->where('post.title', 'LIKE', '%' . $searchInput . '%')
->orWhere('tag.title', 'LIKE', '%' . $searchInput . '%')
->orderBy('post.created_at', 'desc')
->groupBy('post.id')
->with('tags')
->paginate(8);
这种代码(有点)有效。假设我有一篇文章,标题是这是一个测试主题
,标签是CSS
和HTML
- 当我搜索
或测试
时,我找到了帖子,这里没有问题主题
- 当我搜索
或CSS
时,我找到了帖子,这里没有问题HTML
test
和CSS
时,我没有找到帖子。此外,当我搜索CSS HTML
时,我没有得到任何结果
我希望有人能帮助我优化这个搜索查询,这让我很头疼。我会尝试一个查询范围。然后使用您的关系查询其余的
class Post extends Eloquent {
public function tags()
{
return $this->belongsToMany('Tag');
}
public function scopeTitle($query, $title)
{
return $query->with('title', '=', $title);
}
}
然后您可以使用如下模型:
Post::title('Post Title')->tags();
如果您的多对多关系设置正确,这将通过标题以及与之相关的所有标记获取帖子。我找到了答案,这可能对其他人有用。以下是代码:
$posts = Post::join('post_tag', 'post_tag.post_id','=','post.id')
->join('tag','tag.id','=','post_tag.tag_id')
->where('post.title', 'LIKE', '%' . $searchInput . '%')
->orWhereIn('tag.title', preg_split('/\s+/', trim($input['query']))) //The fix
->orderBy('post.created_at', 'desc')
->groupBy('post.id')
->with('tags')
->paginate(8);
有多个标签,修复方法是修剪它们并将它们放入一个数组中。然后只需将
orWhere()
更改为orWhere()
是的,我已经在工作了,这不是我的问题。我想按标题或相关标签搜索所有帖子。另外,我想您可以选择whereTitle('title'):-)。