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

标签 php mysql laravel eloquent relationships

我有三个模型

文章

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 我想让它成为一个用户对象

看到这张照片,这就是我到目前为止所达到的效果

screen of what i have done

使用 laravel 5.4

最佳答案

您可以使用以下内容:

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

这里 'user' 是你在 User 的评论模型中提到的关系。

关于php - 如何通过中间表在从一个模型到另一个模型中使用 Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283879/

相关文章:

php - 使用php和MySQL在数据库中存储多个长文本时的注意事项

php - 具有相关数据的旧数据库,我的 mysql 查询有问题

php - Return Back 在 Excel::load() 函数中起作用:Laravel 4.2

mysql - 私有(private),群组和公共(public)聊天需要数据库结构 - MySQL

php - 优化MySQL搜索查询

从 excel 文件读取日期字段的 PHPExcel 问题

php - 如何在 php 中 move_uploaded_file 时重命名文件?

php - HTML 输入 : uploading multiple files maxes at 20

php - 错误: `Trying to get property of non-object` in PHP upload from AngularJS

Laravel 5.6 - 在此服务器上找不到请求的资源/home