Limit many to many relationships.
Hello guys, I'm trying to limit a many to many relationship with the following code:
$latest = Manga::including(['chapters' => function($q) {
$q->descending('number');
$q->limit(1);
}])->limit(24)->all();
query result:
[
...
{
...
updated_at: "2020-10-29 21:41:13",
chapters: [ ] //empty
},
{
...
updated_at: "2020-10-29 21:41:39",
chapters: [
{
id: "1528",
number: "398",
name: "",
manga_id: "5",
created_at: "2020-10-29 21:42:50",
updated_at: "2020-10-29 21:42:50"
}
}
]
but it only work for 1 manga record with id 5, I don't know whats wrong, can u guys tell me?
P.S: sorry bad english.
Hi,
Unfortunately limits don't quite work as expected on eager loading queries. The limit will limit the total number of related records being loaded not the number of records loaded for each parent. I have been looking into a solution but it is difficult to implement something that works across all database types.
A temporary solution could be something like this (I have not tested the code):
$latest = Manga::including(['chapters' => function($q) {
$q->select(['*', new Raw('MAX(number)')]);
$q->groupBy('manga_id');
}])->limit(24)->all();
You can try this as well. See if it works ? Havent tested the code.
$latest = Manga::select('mangas.*') ->join('chapters', function ($join) { $join->on('chapters.manga_id', '=', 'mangas.id') ->where('chapters.number', '=', DB::raw('(SELECT MAX(number) FROM chapters WHERE chapters.manga_id = mangas.id)')); }) ->limit(24) ->get();