2016-12-21 79 views
4

是否有可能在超過1級的深層級上使用Eloquent進行多級關係查詢?我的表是這樣的:laravel多級關係

post_comments-> ID |評論| POST_ID | user_ID的| ...

post_comment_replies-> ID |回覆| post_comment_id | user_ID的| ...

用戶 - > ID |名稱| ....

user_data-> ID |頭像| ...

所以我想問的是有可能得到評論郵政與所有回覆和用戶數據的人誰回覆了1條查詢與Eloquent評論。

這是示範如何我評論是這樣的:

class PostComment extends Model{ 
public function replies(){ 
    return $this->hasMany(PostCommentAwnsers::class); 
} 

public function user() { 
    return $this->belongsTo(User::class); 
} 
public function userInfo(){ 
    return $this->belongsTo(UserInfo::class,'user_id','user_id'); 
}} 

public function index($id){ 
    $posts = Post::find($id); 
    $postComments = PostComment::where('post_id','=',$id)->paginate(5); 

    return view('post.show',[ 
     'post' => $post, 
     'postComments' =>$postComments 
    ]); 
} 

當我得到所有的用戶數據爲評論我想所有的用戶數據回答的人。 我真的很抱歉,如果這已經awnsered或其他地方記錄,但我似乎無法找到這個問題的確切解決方案。

+0

你確定'user_data'需要在一個單獨的表中嗎?如果它是一對一關係,則應合併這兩個表。 –

+0

是的,但它包含很多列,我只在這個項目中使用user_data表中的幾個例子,我不想調用所有的用戶數據,我只需要用戶名和名稱 – Radi

+0

你只能查詢('id','=',$ id) - > select('firstname','lastname') - > get()'https://laracasts.com /index.php/discuss/channels/eloquent/select-specific-columns-using-eloquent-orm?page=1 –

回答

7

你應該尋找積極加載:https://laravel.com/docs/5.3/eloquent-relationships#eager-loading,如果你想獲得的所有信息及其評論,

$posts = Post::with('comment')->get(); 

,如果你想與評論的評論和回覆的所有帖子:

$posts = Post::with('comment.reply')->get(); 
+0

謝謝!這幫助我解決了我的問題。 – Radi

+0

我該怎麼辦如果我想要回復的次數? –