Laravel搜索标题和相关标签

时间:2014-10-21 21:53:14

标签: 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.title', 'LIKE', '%' . $searchInput . '%')
             ->orWhere('tag.title', 'LIKE', '%' . $searchInput . '%')
             ->orderBy('post.created_at', 'desc')
             ->groupBy('post.id')
             ->with('tags')
             ->paginate(8);

此代码(种类)有效。假设我的帖子标题为This is a test subject,标签为CSSHTML

  • 当我搜索testsubject时,我会找到帖子,此处没有任何问题。
  • 当我搜索CSSHTML时,我会找到帖子,此处没有任何问题。

当我搜索上述两者的组合时(例如,当我搜索testCSS时,我找不到帖子。另外,当我搜索CSS HTML时,我不会#39; t得到任何结果。

我希望有人可以帮我优化这个搜索查询,这让我很头疼。

2 个答案:

答案 0 :(得分:1)

我找到了答案,这可能对其他人有用。这是代码:

$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()更改为orWhereIn()

答案 1 :(得分:0)

我会尝试查询范围。然后用你的关系来查询其余的......

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();

如果您的“多对多”关系设置正确,这将获得标题的帖子,然后是与之关联的所有标签。

相关问题