Laravel eloquent relationships user group posts
سؤال
I am trying to get the users group, and include the post on that group.
This returns the users groups, but the groups must contain the posts of the group too. a post has group_id to where it is posted
My code to get the user:
return User::find(1)->groups;
My User model:
public function groups()
{
return $this->belongsToMany('Group');
}
My group model:
public function posts()
{
return $this->hasMany('Post');
}
المحلول
Here's what you need: return User::with('groups', 'groups.posts')->find(1);
Check out nested eager loading at the bottom of the section on http://laravel.com/docs/eloquent#eager-loading
نصائح أخرى
You need to specify the relation to retrieve with your user, for example :
$user = User::with('groups')->find(1);
Also I would recomend to specify the keys in your relations for performance boost.
Also if you need nested with you can do this way:
$user = User::with('groups.posts')->find(1);
This will load User with groups and also posts in that group. It's stated in laravel docs. See this: eager loading