Laravel雄辩地获得相关表的最新行 [英] Laravel eloquent get the latest row of related table
问题描述
我有两个表,书和章。一本书有很多章。
I have two tables, books, and chapters. One book has many chapters.
书模型:
public function chapters() {
return $this->hasMany(Chapter::class);
}
章节模型:
public function book() {
return $this->belongsTo(Book::class);
}
我想使用像这样的单个查询来获取带有自己最新章节的图书清单:
I want to get book list with their own latest chapter using single query like this:
$books = Book::with(['authors', 'categories', 'chapters' => function($q) {
$q->orderBy('updated_at', 'desc')->first();
}]->get();
但是它不起作用。各章返回一个空数组。如果我删除了 first()子查询,它可以正常工作。
But it doesn't work. Chapters return an empty array. If I remove first() in the subquery, it works properly.
有什么方法可以只执行一个查询吗?我不想让所有相关的章节都保留一章,或者使用多个我感觉更好的唯一方法是使用 join ,对吗?
Are there any way to do this with just one query. I don't want to get all related chapters then keep one, or using multiple queries. The only way I feel better is using join, is it right?
任何帮助将不胜感激。
推荐答案
由于关系是单独的查询,因此无法为急切加载的关系添加限制,如果这样做,则会限制整个关系查询,它不会成为每个相关对象的限制。
Because relationships are separate queries, you can't add a limit to an eager loaded relationship. If you do, this limits the entire relationship query, it does not act as a limit per related object.
幸运的是,您的要求可以简单地通过附加关系来实现:
Luckily, your requirement can be implemented simply with an additional relationship:
public function latestChapter() {
return $this->hasOne(Chapter::class)->latest();
}
现在,而不是急于加载整个章
关系,您可以只希望加载新的 latestChapter
关系。
Now, instead of eager loading the entire chapters
relationship, you can just eager load your new latestChapter
relationship.
$books = Book::with(['authors', 'categories', 'latestChapter'])->get();
这篇关于Laravel雄辩地获得相关表的最新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!