Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gella's avatar
Level 1

Grouping related models by pivot

I'm trying to group related model by pivot data, but this returns only one record of the related for each group. How can I group quiz records by column parent, which is saved in pivot table?

$user = User::where('id', $id)
->with(['quiz' => function($query) use ($md) {
    $query->where('md_id',$md)->groupBy('pivot_parent');
}])
->first();
0 likes
5 replies
rodrigo.pedra's avatar

Just guessing, but do you want to group for presentation purpose? Or for calculation/statistics purpose?

Does the pivot_parent columns references to the primary id in the quiz table or is it some other value?

gella's avatar
Level 1

For presentation. pivot_parent refers to parent, a column in the pivot table:user_quiz

rodrigo.pedra's avatar
Level 56

groupBy on the relation eager loading will apply the GROUP BY clause on the SQL query executed to fetch the quiz records.

Try grouping after fetching

    $user = User::query()
        ->where('id', $id)
        ->with([
            'quiz' => function ($query) use ($md) {
                $query
                    ->withPivot('pivot_parent')
                    ->where('md_id', $md);
            },
        ])
        ->first();

    $grouped = $user->quiz->groupBy('pivot_parent');

This will group the query results. You will end up with two variables, but if you want only one you can dynamically add to the user instance like this:

    $user->grouped = $user->quiz->groupBy('pivot_parent');
gella's avatar
Level 1

Yes it workss! thank you :)

1 like

Please or to participate in this conversation.