laravel icon indicating copy to clipboard operation
laravel copied to clipboard

Limit in "Eager Loading"

Open joserick opened this issue 2 years ago • 2 comments

Hi,

I need to limit in query in relationship called through "Eager Loading".

/api/v1/posts/1?include=comments

BelongsToMany::make('comments')->relationLoad(
    static fn($query) => $query->limit(5)
);

Is possible?

joserick avatar May 12 '22 00:05 joserick

Hi @joserick, I think you're essentially asking for the same as has been discussed on https://github.com/laravel-json-api/laravel/issues/177 ?

BenWalters avatar May 12 '22 07:05 BenWalters

Thank! @BenWalters, then I will be waiting for the implementation, If there is any other way to implement it without touching the model files that would be great.

joserick avatar May 13 '22 21:05 joserick

As noted in this section of the Eloquent docs on eager loading:

The limit and take query builder methods may not be used when constraining eager loads.

https://laravel.com/docs/9.x/eloquent-relationships#constraining-eager-loads

So this isn't something we'd be able to support.

You need to think about the design of the API. If a relationship could return far too many related resources for it to be viable for that relatinoship to be loaded without constraints, then it should be a "links only" relationship with the related data always paginated to prevent the client from getting way too many results. That's discussed in my comment here: https://github.com/laravel-json-api/laravel/issues/177#issuecomment-1086128918

lindyhopchris avatar Sep 15 '22 18:09 lindyhopchris