Tuesday, May 23, 2017

How to use Laravel Eloquent to query a minimum number of related models using groupBy and havingRaw

I want to select a user only if they have more than 10 trips, where the trip must have a walking leg.

Table structure

// users
(int) id

// trips
(int) id
(fk) user_id

// legs
(int) id
(fk) trip_id
(str) mode

Models

class User extends Model
{
    public function trips()
    {
        return $this->hasMany(Trip::class);
    }
}

class Trip extends Model
{
    public function legs()
    {
        return $this->hasMany(Leg::class);
    }
}

I can return a user that has trips where there is a walking leg ...

$user = User::where('id', '=', 1)
    ->whereHas('trips', function($query) {
        ->query('legs', function($query) {
            $query->whereHas('mode', '=', 'walk');
        });
    })
    ->first();

... and it seems that it can be done using groupBy() and havingRaw('COUNT(*) > 10') ...

$query = User::whereHas('trips', function ($query) {
    $query
        ->whereHas('legs', function ($query) {
            $query->where('mode_id', '=', 2);
        })
        ->groupBy('id')
        ->havingRaw('COUNT(*) > 10');
});

... but this is where I'm stuck.

Any help much appreciated, thanks!



via darronz

Advertisement