Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel multilevel relations

Is it possible to make a multi level relation query with Eloquent on a deeper level than 1 level? My tables look like this :

post_comments-> id|comment|post_id|user_id|...

post_comment_replies-> id|reply|post_comment_id|user_id|...

users-> id|name|....

user_data-> id|avatar|...

And so I want to ask is it possible to get the Comments for a Post with all the Replies and the User Data for the person who replied to a comment in 1 query with Eloquent.

This is how my Comments Model looks like:

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
    ]);
}

And as I get all the user data for a Comment I want to get all the user data for the person who replied. I am really sorry if this has been awnsered or documented somewhere else but I just can't seem to find the exact solution to this problem.

like image 448
Radi Avatar asked Dec 21 '16 08:12

Radi


1 Answers

You should look for eager loading : https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

if you want to get all posts and their comments :

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

and if you want all posts with comments and replies of the comments :

$posts = Post::with('comment.reply')->get();
like image 117
ᴄʀᴏᴢᴇᴛ Avatar answered Oct 04 '22 14:10

ᴄʀᴏᴢᴇᴛ