Skip to content
Advertisement

Many-to-many relation Laravel Eloquent. Fetch related table with specific related id

I am writing a query in Laravel 8 using Eloquent. There is a many-to-many relation between subjects and streams and their pivot table is courses.

subjects: id name

streams id name

courses id subject_id stream_id

I have to fetch subjects with specific stream.

I have written the following query.

$this->subjects = Subject::has(‘streams’,$this->stream)->get();

I am having problem in this.

courses table :

id stream_id subject_id
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 3 1

This is the sample data. If I want to fetch subject where stream id is 1 then it is only fetching subject with ids 3 and 4 and not fetching subjects with id 1 and 2. Can anyone explain me why it is skipping subject ids with 1 and 2 ?

PLease anyone can help me with this. Thank you in advance . 🙂

Edited

class Subject
{
   public function streams()
    {
        return $this->belongsToMany(Stream::class, 'courses', 
'subject_id', 'stream_id');
    }
}


class Stream
{
   public function subjects()
    {
        return $this->belongsToMany(Subject::class, 'courses', 
'stream_id', 'subject_id');
    }
}

Advertisement

Answer

You should specify the table name where you are referencing the id to avoid ambiguity.

$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
    $query->where('stream.id', $stream->id);
})->get();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement