framework icon indicating copy to clipboard operation
framework copied to clipboard

Limit many to many relationships.

Open lsfratel opened this issue 5 years ago • 3 comments

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.

lsfratel avatar Oct 30 '20 12:10 lsfratel

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.

freost avatar Oct 31 '20 07:10 freost

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();

freost avatar Nov 01 '20 13:11 freost

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();

shameellamba avatar Jul 02 '24 13:07 shameellamba