eloquent - Laravel 6与()的关系
问题描述
我有一个帖子模型,它有很多评论,每条评论都有一个用户模型。如果我跑
@foreach( $post->comments as $comment )
<div>{{ $comment->text }} <br>{ $comment->user->name }}</div>
@endforeach
它为评论 foreach 中的每个循环向用户生成一个查询。如何编写这段代码,让 Laravel 只对所有用户进行一次查询?
控制器代码看起来像
public function detail(Post $post)
{
return view('home.detail')->with([
'post' => $post->with('comments', 'comments.user')->get()->first()
]);
}
非常感谢。
解决方案
推荐阅读
- c# - 为什么 jQuery Ajax 调用在 Azure 上不起作用?
- flutter - Flutter:蓝牙设备
- python - Python中不同因素的正态性检验
- c# - 如何缓存 xsd xschemaset 以验证不同的 XML
- logstash - 如何检查json字符串中的键值对以获取logstash中的消息字段
- html - 带有复选框选项的 React Dropdown Modal-ish - 按部分分隔
- javascript - 我的循环如何返回 100?我很困惑
- r - 下标越界,需要 SDM 帮助
- python - 实现 SSL 证书的 Python 套接字
- catboost - 将目标编码值传递给 CatBoost