dqdjfb2325 2017-09-18 16:11
浏览 36
已采纳

如何通过中间表在一个模型中使用Eloquent到另一个模型

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

  • 写回答

2条回答 默认 最新

  • doumao8355 2017-09-18 16:23
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?