Reputation: 2355
I have 3 Model named User
, Post
, Comment
and this models are related.
User Model : This model has many Post model.
Post Model : This model belongs to User model and has many Comment model.
Comment Model : This model belongs to Post model and User model.
Now the question is how can i get all posts that a user commented on?
Upvotes: 1
Views: 2267
Reputation: 180024
whereHas is what you're looking for:
$posts = Post::whereHas('comment', function($query) use($user) {
$query->whereUserId($user->id);
})->get();
$user
would be the user you're interested in.
Upvotes: 5
Reputation: 881
add to user
function comments() {
return $this->hasMany(Comment::class);
}
and
User::find(1)->comments->map(function ($comment) { return $comment->post; })->unique();
Upvotes: 0