2017-03-27 67 views
1

我是Laravel的新手, 讓我直接回答這個問題。Laravel DB查詢:獲取一對多多維數組結果

假設我有「帖子」表和「評論」表

而第一個「郵報」有3條評論,

什麼是最好的查詢方法來實現這種結果

Post => (
    [0]=> array (
     [id]=>1 
     [content]=> This is my first Post! 
     [comments]=> array(
     [0]=>array(
      [id]=>1 
      [post_id]=>1 
      [content]=> First comment! 
     ) 

     [1]=>array(
      [id]=>2 
      [post_id]=>1 
      [content]=> Second comment! 
     ) 

     [2]=>array(
      [id]=>3 
      [post_id]=>1 
      [content]=> Third comment! 
     ) 


    ) 
    ) 
) 

回答

1

急於負載的關係:

$posts = Post::with('comments')->get()->toArray(); 
+0

它得到一個錯誤,說「不明身份的意見」 – Angger

+0

Mazenin:請幫助:( – Angger

+0

@Angger您需要定義' hasMany()'關係首先使它工作。 –