L
L
lolrofl012018-11-13 22:37:05
Laravel
lolrofl01, 2018-11-13 22:37:05

How to build relation between three tables in laravel?

There are 3 tables: articles, comments, users. The connection is this - an article can have many comments:

public function comments()
    {
        return $this->hasMany('App\Comments');
    }

And each comment has 1 user. (users model)
public function comments()
    {
        return $this->hasMany('App\Comments', 'user_id');
    }

How do I get all the data from the users table in the comment selection for a particular article? So far, this code selects all the comments on the article:
$comments = Posts::where('id', $news->id)->first()->comments;

What should be added to it so that in $comments, in addition to comments, there is info from the users table? Those. I want to make an analogue of join using eloquent.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2018-11-13
Hrebet @hrebet

https://laravel.com:Polymorphic Relations

M
miki131, 2018-11-14
@miki131

$comments = $news->comments()->with('user')->get();

or
$post = Post::with('comments', 'comments.user')->where('id', $id)->first();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question