bufferoverflow's avatar

Using ->limit() in ORM eager loading bug or I am using it incorrectly?

The following simple query pretended to retrieve all Sites with their Url preloaded, max 2k per site.

But instead it applies the limit globally, and looks like a bug? If the first site already has 2k urls, the rest of sites are retrieved with 0 urls.

Site::query()
    ->where('active', true)
    ->with(['urls' => function ($query) {
        $query
            ->whereNull('fetched_at')
            ->fromActiveSitemap()
            ->limit(2000);
    }]);

I think I ran with this issue in the past, so this is behaving like this for a long time. Is this a bug or is there something I'm not understanding about the query?

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

You cannot limit relations in this way. Eloquent does two seperate queries, one for the sites and one for the urls

The limit statement is applied to the urls and the result set contains 2000 records max, not 2000 per site

There is a package that can help https://github.com/staudenmeir/eloquent-eager-limit

2 likes

Please or to participate in this conversation.