Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get model with relation's pivot condition

I need to get all appeals, that have appeal_stage.expiration_date less than NOW().

enter image description here

Now I have following solution:

public function scopeExpired($query) {
    $query->join('appeal_stage', 'appeals.id', 'appeal_stage.appeal_id')
        ->where('appeal_stage.expiration_date', '<=', new Expression('NOW()'));
}

but resulted model dump shows that joined table is recognized as pivot table: enter image description here

So, I want to ask - Is there some more convenient way to perform this request? My suggestions is use Illuminate\Database\Eloquent\Relations\Pivot somehow, bu I do not quiet understand, how Pivot can be used here.

UPD 1

Models has next relations:

public function stages()
{
    return $this->belongsToMany(Stage::class)->withPivot('prolongated_count', 'expiration_date')->withTimestamps();
}

public function appeals() {
    return $this->belongsToMany(Appeal::class);
}
like image 830
Oleg Shakhov Avatar asked Sep 19 '25 03:09

Oleg Shakhov


1 Answers

You should be able to do something like this:

$appeal->stages()->wherePivot('expiration_date', '<', $now)->get()
like image 85
kerrin Avatar answered Sep 20 '25 19:09

kerrin