scott
scott

Reputation: 3202

How to retrieve all data using relation?

i have three tables

users
posts
comments

my question is how to retrieve user post and post comments in single query .

thank you in advance

Upvotes: 1

Views: 105

Answers (2)

user4294557
user4294557

Reputation:

Your question answer has already given by @ Nicklas Kevin Frank .

for getting following error FatalErrorException in Model.php line 867: Class 'Post' not found error ,in your model class modify your hasmany to this: App\User

<?php

class User extends Model
{

public function posts()
    {
        return $this->hasMany('App\Post');
    }

}

in posts model

<?php

class Post extends Model
{

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }


}

in comments model

<?php

class Comment extends Model
{

    public function posts()
    {
        return $this->belongsTo('App\Post');
    }
}

and in your controller

$data = User::findOrFail(1)->posts()->get();

Upvotes: 4

Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

You can use the following:

User::find($id)->with('posts','posts.comments')->get();

This way you get a user, and his posts and comments on said posts.

To only access posts which belongs to a user you must do the following:

User::find($id)->with('posts')->get();

Upvotes: 1

Related Questions