2017-08-04 108 views
0

這是一個問題和我自己的答案(我偶然發現的解決方案)。 Laravel的文檔沒有提到這一點,它給我帶來了幾個小時的編程痛苦。Laravel渴望加載內部約束不受限制,如果後面嵌套'與'

比方說,我們有評論和投票(評論)的職位。 Laravel最喜歡的例子。模型和關係是教科書(來自Laravel的文檔)。帖子有評論,評論有投票。

所以,

$comments_ids = [1,6,7,22]; 

Post::where('id', $post_id) 
      ->with(['comments' => function($query) use ($comments_ids) { 
       $query->whereIn('id', $comments_ids); 
      }]) 
      ->with('comments.votes') 
      ->first(); 

所以,我應該期待用後其意見,IDS是1,6,7,22和選票渴望加載。

但不是那麼快!我收到所有評論!他們全部! ...爲什麼?

回答

0

下面是這個問題的答案:

因爲,我們渴望負載意見,然後我們加載票,得票強制所有評論加載。

此:

$comments_ids = [1,6,7,22]; 

Post::where('id', $post_id) 
      ->with(['comments' => function($query) use ($comments_ids) { 
       $query->whereIn('id', $comments_ids); 
      }]) 
      ->with('comments.votes') //this forces Builder to completely ignore whereIn clause above. 
      ->first(); 

應該寫成如下:

$comments_ids = [1,6,7,22]; 

Post::where('id', $post_id) 
      ->with(['comments' => function($query) use ($comments_ids) { 
       $query->whereIn('id', $comments_ids) 
         ->with('votes'); //eager load votes with filtered comments 
      }]) 
      ->first(); 

然後你會得到在$ comments_ids變量指定ID的註釋。並投票熱切與他們。

這個小小的細微差別引起了很多頭痛。