sql - 在 Laravel 中使用 Eager Loading 查询构建器 Eloquent
问题描述
有一个典型的带有帖子和评论的 squeme,其中一个帖子有很多评论,一个评论属于一个帖子:
岗位型号:
public function comments(){
return $this->hasMany('App\Comment');
}
迁移后:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
评论型号:
public function Post(){
return $this->belongsTo('App/Post', 'id');
}
评论迁移:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->date('date_comment');
$table->unsignedInteger('post_id')->nullable()->default(null);
$table->foreign('post_id')->references('id')->on('posts');
});
我想在 Laravel 中使用急切加载。
例如。如何使用急切加载获取所有包含他最近评论的帖子?
我试过这个:
$post = Post::with('comments:post_id, date_comment')->get();
但是像这样我得到了所有的评论。请问有什么帮助吗?
此致
编辑:
foreach 语句(刀片):
@foreach($posts as $post)
<td>{{ $post->name }}</a></td>
<td>
{{ !empty($post->comments[0]) ? $post->comments[0]->
date_comment : '' }}
</td>
@endforeach
解决方案
您需要再建立一个关系才能检索最新评论。
Post.php
public function comments(){
return $this->hasMany('App\Comment');
}
public function latestComment(){
return $this->hasOne('App\Comment')->orderBy('date_comment', 'desc');
}
现在您可以像这样检索它。
$posts = Post::with('latestComment')->get();
注意:未经测试。
推荐阅读
- react-native - 重定向链接不正确(在 expo 应用程序中发现身份验证)
- rabbitmq - 为什么要用rabbitMQ代替ocelot api gateway
- powershell - 使用powershell将文本文件数据转换为excel
- java - 如何将 HtmlLink 上传到 Android WebView
- c++ - 无法识别文件“Lenna.jpg”的格式。在抛出 'cimg_library::CImgIOException' 的实例后调用终止
- typo3 - DDEV-Local 403 Forbidden on provided URL with ddev start 或 ddev launch(docroot 错误)
- android - 在 ScrollView 中设置 GridLayout 时布局拉伸
- c# - 仅显示活动记录并使用 linq c# 删除过期记录
- c++ - OpenGL:圆柱体在旋转 90 度后变形
- java - 房间数据库迁移问题