phpmysqllaraveleloquentrelationships

How To use Eloquent in From One Model to another model through intermediate table


i have three models

Article

id 
title 

Comment

id
title
user_id
article_id

User

id 
name

what i wanna achieve is to select one article based on its id with comments and user info that made that comment

like that :

$article = Article::find($id -- say 1)->with('comments' -- this is a relation in Article Model)->get(); 

this gives me article with related comments as an array of objects say comment one - comment two etc ....

what i want instead of user_id in comment object i wanna it to be a user object

see this pic thats what i reached so far

screen of what i have done

using laravel 5.4


Solution

  • You can use following:

    $articles = Article::find($id)->with('comments', 'comments.user')->get();
    

    Here 'user' is the relationship you mentioned in the comments model for User.