Issue
I searched a lot but could not find any answer about it, so I hope you could help me!
I have three tables: posts
, users
and post_users
.
Post_users
contains two columns: user_id
and post_id
.
I need to get all posts by an user with Eloquent. Any ideas?
Solution
Model User
:
public function posts()
{
return $this->belongsToMany('App\Post', 'post_users', 'user_id', 'post_id');
}
Model Post
:
public function users()
{
return $this->belongsToMany('App\User', 'post_users', 'post_id', 'user_id');
}
Try:
$user = User::find($id);
$allpost = $user->posts()->get();
var_dump($allpost);
Answered By - mydo47
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.