【问题标题】:Laravel search for title and related tagsLaravel 搜索标题和相关标签
【发布时间】:2014-12-17 06:53:09
【问题描述】:

我想按标题和相关标签搜索帖子,这些标签与帖子具有多对多的关系。我走了很远,但有些事情让我感到困扰。这是我的代码:

$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 时,我没有得到任何结果。

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

【问题讨论】:

    标签: search laravel tags many-to-many eloquent


    【解决方案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()

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 是的,我已经有这个工作了,这不是我的问题。我想按标题或相关标签搜索所有帖子。另外,我认为你提到了 whereTitle('title') :-)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多