2014-10-21 165 views
0

我想搜索標題和相關標籤的帖子,這些標籤與帖子具有多對多的關係。我來到相當遠的地方,但有些東西讓我困擾。這裏是我的代碼:Laravel搜索標題和相關標籤

$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我沒有得到任何結果。

我希望有人可以幫助我優化這個搜索查詢時,它讓我頭疼。

+0

任何任何想法? – JasonK 2014-10-22 14:34:05

回答

0

我找到了答案,這可能對其他人有用。這裏是代碼:

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

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

這將獲得由標題的帖子,然後如果你的多對多的關係是正確安裝與它相關的所有標籤。

+0

是的,我已經有這個工作,這不是我的問題。我想通過標題或相關標籤來搜索所有帖子。另外,我認爲你想知道哪裏題('title'):-)。 – JasonK 2014-10-22 07:12:09