saqueib
4 years ago

Limit the result from eager loaded relation

Posted 4 years ago by saqueib

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

Please sign in or create an account to participate in this conversation.