2015-02-09 57 views
0

Laravel 4,其中一個whereHas內 - 先進在哪裏Laravel 4:其中,並使用機鋒

我試圖找回Posts有一個$keyword好比一個Companion再說,我要檢索的Posts的有鏈接titlecontent作爲$keyword。 但是,當我嘗試在whereHas中使用wherewhereIn時,查詢不考慮這些因素。當狀態爲0(不可見)或不在類別1內時,不應選擇郵政項目。

$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%')->lists('id'); 

下面的代碼塊必須做兩件事情:

  1. 搜索Post項目與titlecontent$keyword
  2. 搜索Post項目有Companions$keyword

代碼:

$results = Post::whereHas('companions', function($query) use($companion_id) 
       { 
        $query->whereIn('companions.id', $companion_id) 
         ->where('state', '=', 1) 
         ->whereIn('category_id', array(1)); 
       }) 
       ->whereIn('category_id', array(1)) 
       ->orwhere('title', 'LIKE', '%' . $keyword . '%') 
       ->orWhere('content', 'LIKE', '%' . $keyword . '%') 
       ->where('state', '=', '1') 
       ->orderBy('menu_order', 'desc') 
       ->get(); 

上面的代碼檢索成功地除wherewhereInwhereHas內部數據。

誰能幫我一把嗎?

回答

0

感謝Jarek Tkaczyk。 他的回答幾乎是正確的。我所要做的只是將where包裹在orWhere之內。現在我得到Posts,它有一個Companion$keyword,我得到的Posts具有contenttitle內的$keyword

$results = Post::whereHas('companions', function($query) use($companion_id) 
       { 
        $query->whereIn('companions.id', $companion_id) 
        ->where('state', '=', '1'); 
       }) 
       ->orWhere(function($q) use ($keyword) { 
        $q->where('title', 'LIKE', '%' . $keyword . '%') 
         ->orWhere('content', 'LIKE', '%' . $keyword . '%'); 
       }) 
       ->whereIn('category_id', array(1, 3)) 
       ->where('state', '=', '1') 
       ->orderBy('menu_order', 'desc') 
       ->get(); 
2
  1. 包裝您orWhere子句(..)
  2. 你不需要wherewhereInwhereHas關閉,因爲它查詢companions
  3. 你不需要whereIncategory_id,除非你想傳遞有多個ID

$results = Post::whereHas('companions', function($query) use($companion_id) 
    { 
     $query->whereIn('companions.id', $companion_id); 
    }) 
    ->whereIn('category_id', array(1)) // why not where(..) ? 
    ->where(function ($q) use ($keyword) { 
     $q->where('title', 'LIKE', '%' . $keyword . '%') 
     ->orWhere('content', 'LIKE', '%' . $keyword . '%'); 
    }) 
    ->where('state', '=', '1') 
    ->orderBy('menu_order', 'desc') 
    ->get(); 
+0

感謝您的回覆。當我嘗試你的代碼時,它什麼都不返回。我基本上想要的是搜索'Posts',其中有'Companion' X,並在'Posts'內容和'title'中搜索關鍵字X.我的代碼確實如此,除非它看起來不是'Companion'並且'Posts'狀態是1,並且它看起來不是'Posts'是否在所需的$ category_id內。 – Kordaat 2015-02-10 08:45:50

+0

@Kordaat是的,這段代碼的確如你剛纔所說的那樣。它返回'posts',其具有'標題或內容,如%關鍵字%'和'category_id = 1'和'state = 1',並且與'companion_id'中的伴侶ID相關。只要確保'$ companion_id'是一個數組,否則只需使用'where'而不是'whereIn'。你的代碼返回了不同的結果,因爲它不關心你的大部分'where'子句,因爲* random *'或'placement。 – 2015-02-10 09:30:07

+0

所有我不得不改變的是第一個「去哪裏」或「哪裏」。 'Posts'和'companions'都有'state',所以它們都需要。我已經發布了下面的正確代碼。 – Kordaat 2015-02-10 09:40:24