我有三个模型
文章
id
title
评论
id
title
user_id
article_id
用户
id
name
我想要实现的是根据文章的 ID 选择一篇文章,其中包含评论和发表该评论的用户信息
像那样:
$article = Article::find($id -- say 1)->with('comments' -- this is a relation in Article Model)->get();
这给了我带有相关评论的文章作为对象数组,比如评论一 - 评论二等....
我想要的不是评论对象中的 user_id 我想让它成为一个用户对象
看到这张照片,这就是我到目前为止所达到的效果
使用 laravel 5.4
最佳答案
您可以使用以下内容:
$articles = Article::find($id)->with('comments', 'comments.user')->get();
这里 'user' 是你在 User 的评论模型中提到的关系。
关于php - 如何通过中间表在从一个模型到另一个模型中使用 Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283879/