0
votes

I searched endlessly for a question that answered my question here and I didn't find it. My question is as follows, I have 3 models: User, Post and Comments. Where user has a relationship with one to many posting, and Post has a relationship with one to many comments as well. How can I get all of the user's comments on all posts? Currently my solution looks like this:

Models Users:

    public function comments(){
        $comments = array();

        foreach ($this->posts()->get() as $el) {
            foreach ($el->posts()->get() as $nEl) {
                array_push($comments, $nEl);
            }
        }
        return collect($comments);
    }

I would like a less expensive and native solution for laravel, if any.

1
Check has many through in docs. Always keep in mind laravel's proposed naming convention to avoid most of problems (i.e. singular/plural, lowercase/uppercase etc). Btw, this your situation is elementary hasManyThrough relation. - Tpojka

1 Answers

1
votes

On your User model, something like:

public function getComments()
{
    return Comment::whereHas('posts', function ($query) {
        $query->where('user_id', $this->id);
    })->get();
}

Also see: https://laravel.com/docs/6.x/eloquent-relationships#has-many-through