Sunday, February 20, 2022

[FIXED] Set limit to eloquent relationship

Issue

This is my query.

$helpCategoryList = HelpCategory::where('is_active', 1)
                               ->with(['helps' => function($query) {
            $query->with(['users'])
                  ->withcount(['helpComments','helpResponse','helpVotes'])
                  ->limit(5);}])
           ->orderBy('created_at', 'asc')
           ->get()
           ->toArray();

It gives totally 5 records from helps table,but i need each category 5 records of help details. So each category has many helps.


Solution

it's bit late but try my solution for once I hope it will work

$helpCategoryList = HelpCategory::where('is_active', 1)
                            ->with('helps')->whereHas('helps',function($query) {
                                    $query->with(['users'])
                                    ->withcount(['helpComments','helpResponse','helpVotes'])
                                      ->take(5);})
                            ->orderBy('created_at', 'asc')
                            ->get()
                            ->toArray();


Answered By - Mr. Pyramid

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.