saqueib's avatar

Limit the result from eager loaded relation

I am building an API which needs below post data with many eager loaded relation. Here is how I have tried, its working but I can't limit the number of replies, adding ->limit(1) is not giving any effect.

How I can optimize query is so slow (taking 5 sec in local machine) since its returning huge data.


return $postRepo->with([
            'replies' => function($q) {
                $q->with(['user' => function($q) {
                    $q->with(['currentCompany' => function($q){
                        $q->addSelect(['id', 'name', 'logo', 'points']);
                    }])
                    ->select(['id', 'first_name' ...]);
                }])
                ->where('status', 'Public')
//***************** Adding Limit clause not working *****************//
                ->select(['id', 'title', 'body', ...])
                ->orderBy('id', 'desc');
            },
            'tags' => function($q) {
                $q->select(['id', 'name']);
            },
            'topic' => function($q) {
                $q->addSelect(['id', 'name', 'category']);
            },
            'user' => function($q) {
                $q->addSelect(['id', 'first_name', ...]);
            }])
            ->where([
              'status' => 'Public'
            ])
            ->paginate( intval(config('listing_qa_per_page', 20)), 
               ['id', 'title', ...]);

Is there any other way to do this, I am using laravel LengthAwarePaginator and I don't know how to add custom data in paginate collection.

One way will be to first get the post then loop over and load all the realations needed. but I will lose the pagination. Please help

0 likes
1 reply
pmall's avatar

First, if you need to format json output, use a package like fractal instead of many selects, it is much more flexible.

Then, you cant limit eager loading, it is not compatible with the core mechanism of eager loading (selecting all related rows with a in clause on the foreign key). Try to have another way of limiting results like only the replies of the last week or something like this.

Please or to participate in this conversation.