php - Laravel - 加入评论、帖子、用户
问题描述
我正在尝试返回每个帖子的作者,以及每个帖子的作者评论。这就是我所做的:
控制器:
$posts = Post::with('comments', 'user')->latest()->paginate(3);
邮政模型:
public function comments() {
return $this->hasMany('App\Comment');
}
public function user() {
return $this->belongsTo('App\User');
}
评论模型:
public function users() {
return $this->hasOne('App\User');
}
这将返回每个帖子及其作者和评论,但不返回评论的作者。
我还应该怎么做??
解决方案
我不会更深入地建立一种雄辩的关系。我希望您已正确设置它。
让我们专注于查询:
Post::with('comments', 'user') -> Returns post with comments and who created it. Which is correct but now what you want.
更新您的代码
$posts = Post::with(['user',
'comments' => function($q) {
$q->with('user'); //Rename users to user in eloquent model. }
])->latest()->paginate(3);
注意:未测试。试试看。
推荐阅读
- terminal - 使用 ls -R 仅显示第一级文件的终端命令
- java - Spring Boot保存将学生分配到组
- node.js - 如何调试在 docker 容器内运行的节点程序
- c++ - boost变体可以为非活动变体调用析构函数吗?
- python - Python:UnicodeDecodeError:'utf-8'编解码器无法解码位置 37 的字节 0x96:无效的起始字节
- java - 消费 Post 方法 Rest + SpringBoot
- android - 为什么我的 webview 应用程序正在下载 .bin 文件?
- ember.js - Ember 保存数据以存储和显示,无需服务器 api
- html - Mojave Html Mail 暗模式:防止某些元素被更改
- android - 当我的应用程序关闭时,如何以编程方式防止设备关闭显示器(屏幕超时)?