Saeed Vaziry
Saeed Vaziry

Reputation: 2355

Laravel get all posts that a user commented on

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

Answers (2)

ceejayoz
ceejayoz

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

Dry7
Dry7

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

Related Questions