2016-08-21 82 views
0

Post :: with('comments.owner') - > get();嵌套預先加載約束

此查詢將爲我們提供所有帖子,其評論和評論所有者。

但是我怎麼能得到所有的帖子,其最後5條評論和作者的每個評論。任何人都可以幫忙嗎?

這裏是架構 帖子 - 標識 - 內容 評論 - ID - commented_id(USER_ID) - user_id說明 用戶 - ID - FULL_NAME 感謝

+0

請發表您的數據庫模式 – jaysingkar

+0

發佈 - id - content 評論 - id - commented_id(user_id) - user_id User - id - full_name – maj

+0

https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-model s-per-parent/ –

回答

1

試試這個:

$posts = Post::with(['comments'=>function($query){ 
       $query->orderBy('created_at','desc')->limit(5); 
      }]) 
      ->with('comments.author') 
      ->get(); 
+0

對不起,這沒有按預期工作。它返回所有評論。我只需要最後5 請參閱下面的查詢跑 SELECT * FROM'posts' SELECT * FROM'comments'其中'在( '6', '7','評論.'post_id' '8' ,'9','10','11','12','13','14','15','16','17','18','19','20',' 21','22','23','24','25','26') – maj

+0

兩條select語句? – jaysingkar

+0

是急切加載不會使用加入。它產生多個查詢 – maj