phplaravellaravel-5eloquentlaravel-4

Consultation through relationships in laravel


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.


Solution

  • 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