Cruze
Cruze

Reputation: 220

Laravel Eloquent to get parent, child records and child records

I have these models having the following fields enclosed in brackets. User can have many post and post can have many categories. How can we achieve to get these using laravel eloquent.

User   [id, name]
Post   [id, user_id, post_title]
PostType [id,post_id, category_desc]

In User model

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

In Post model

public function categories(){
   return $this->hasmany('App\PostType');
}

In Controller

$result = User::with('post')->get();

which will return users, with each user having a records of post. But how to add the categories in the results set?

Upvotes: 0

Views: 2492

Answers (2)

eResourcesInc
eResourcesInc

Reputation: 1028

An alternate solution, especially if you want to bring the posts and post categories every time you grab the user, would be to use the $appends array on the User and Post model to automatically pull those relationships with every query. For example, your Post model would include this at the top:

class Post extends Model
{
    $appends = array('categories');
...

And your User model would look something like this:

class User extends Authenticatable
{
    $appends = array('posts');
...

This will automatically pull in those categories along with the posts any time you pull in a User object.

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35357

You can include distant relations with dot notation:

$result = User::with(['post', 'post.categories'])->get();

Upvotes: 2

Related Questions