Laravel get model with relation's pivot condition

Viewed 7835

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);
}
2 Answers

You should be able to do something like this:

$appeal->stages()->wherePivot('expiration_date', '<', $now)->get()

You should create relationship in appeal model

public function stages()
{
   return $this->belongsToMany(Stage::class,'appeal_stage','appeal_id','stage_id')->wherePivot('expiration_date','<',Carbon::now())->withTimestamps();
}

In belongs To Many relationship second argument is your Pivot table name

Related