Home > Mobile >  Laravel Eloquent withcount compared to other model attribute
Laravel Eloquent withcount compared to other model attribute

Time:11-20

I have a model named

timeslot.

this model has an attribute (integer) named

requested_participants

This model has also a relationship in order to attach participants :

public function participants()
    {
        return $this->belongsToMany(Human::class, 'humans_timeslots', 'timeslot_id', 'human_id');
    }

I want to retrieve records that have less

participants 

than

requested_participants

I tried things like :

Timeslot::withCount('participants')
                            ->having('participants_count','<','requested_resources')
                            ->get();

But this doesn't work !

It works if I use an integer instead of

requested_resources

like :

Timeslot::withCount('participants')
                            ->having('participants_count','<',2)
                            ->get();

but not with this attribute which is part of the same model. Does anyone have an idea?

CodePudding user response:

You can do that using havingRaw method:

Timeslot::withCount('participants')
->havingRaw('participants_count < requested_resources')
->get();
  • Related