Dhruva
1 month ago

How to use Scope for Intermediatble Table in Many to Many Relationships

Posted 1 month ago by Dhruva

Hi All

I am trying to use scope for retrieving column field name from many to many relationship's intermediate table.

Pivot Table fields are

  • quiz_id
  • batch_id
  • start_date
  • end_date
  • points

Model - Quizzes

 public function selectedBatch($batchId)
    {
        return $this->belongsToMany(\App\Batch::class , 'quizzes_batches',  'quiz_id', 'batch_id')
        ->using('App\QuizBatch')
        ->withPivot(
            'start_date', 'end_date', 'points')
        ->wherePivot('batch_id', $batchId)->firstOrFail();
    }

And the scope method is

    public function scopePoints($query)
    {
        return $query->pivot->points;
    }

I want to get points value (the column is in pivot table) from a particular batch (among all batches belongs to quiz).

Now when I try to retrieve following code, I am not getting any result

$quiz->selectedBatch($batchId)->marks();

Please guide me, where I am doing wrong.

Please sign in or create an account to participate in this conversation.