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

makapaka's avatar

How do you group by a relationship column

My query:

              $this->builder = Session::with(['member', 'post.favorite', 'cart.purchases'])
            ->where('created_at', '>=', $dates[0])
            ->where('created_at', '<', $dates[1])
            ->groupBy('member_id')
            ->orderBy('created_at', 'desc');

$dates[] is simply two elements of a start and end date.

Session has 'member_id' on it, so I want to group by the members within the session.

This is giving me error `Syntax error or access violation: 1055 '...sessions.id' isn't in GROUP BY

Any idea how to fix this ?

0 likes
4 replies
bipin's avatar

Use orwhere

        $this->builder = Session::with(['member', 
        'post.favorite', 'cart.purchases'])
        ->where('created_at', '>=', $dates[0])
        ->orwhere('created_at', '<', $dates[1])
        ->groupBy('member_id')
        ->orderBy('created_at', 'desc');
makapaka's avatar

same result, doesn't fix it; that's not the issue, the issue is regarding the groupBy

rick20's avatar

or maybe

Session::with(['member',  'post.favorite', 'cart.purchases'])
        ->whereBetween('created_at', [$dates[0], $dates[1]])
// the rest of your code

as for the error, perhaps change 'strict' => true to 'strict' => false in your config/database.php

Please or to participate in this conversation.