Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kapitan's avatar

Eloquent Relationship Three Tables

I have this models with each fields:

Author (id, name)

Post (id, post, author_id)

Comment (id, comment, post_id)

Can you please help me refactor the eloquent statement below for me to search on the User model with the given "name"?

For example, I want to see the comments that are not "okay" from the post's author with the name of "John".

$comments = Comment::where('comment', '!=', 'okay')->get();

thank you very much in advance.

0 likes
2 replies
MikeMeijer's avatar
Level 6

I think your looking for an hasManyThrough relation.

You can simple add an method on your Author model to fetch an authors comments that goes trough your Post model. Add this your Author model:

public function comments()
{
    return $this->hasManyThrough(
        'App\Comment',
        'App\Post',
        'author_id', // Foreign key on post table...
        'post_id', // Foreign key on comments table...
    );
}

Now you can check if there are comments where comment column is okay by accessing it like this:

$author             = Author::find(1);
$author_comments    = $author->comments()->where('comment',  'okay')->get();

You can change the where clause however you like.

I recommend you to read the information behind this link to understand how this exactly work: laravel.com/docs/5.6/eloquent-relationships#has-many-through

1 like
kapitan's avatar

First, thank you for your reply.

This works if $author returns a single record.

but if $author returns more than one record, it doesn't work.

I have this:

$author = Author::where('name', 'like', '%john%');

am i missing something?

Please or to participate in this conversation.