kapitan
kapitan

Reputation: 2222

Laravel Eloquent - Pivot Table

i have this tables:

Attendances
id | member_id
1  | 1
2  | 2
3  | 3

Members
id | name
1  | Joe
2  | Jane
3  | David

Positions
id | position_name
1  | art
2  | singer
3  | dancer

member_position
member_id | position_id
1         | 2 
1         | 1
1         | 3
2         | 1
2         | 2
3         | 3

From Attendances table, how can i select all who attended that are singers using laravel eloquent?

====EDIT=====

Attendance model:

public function member()
{
  return $this->belongsTo('App\Member');
}

Member model:

public function positions()
{
  return $this->belongsToMany('App\Position');
}

Position model:

public function members() 
{
  return $this->belongsToMany('App\Member');
}

Upvotes: 0

Views: 85

Answers (2)

Oniya Daniel
Oniya Daniel

Reputation: 399

I'm positive this will give you the attendances whose member is a singer, with a nested member relationship model.

$attendances = Attendance::whereHas('member.positions', function($query) {

   $query->where('position_name', 'singers');

})->with('member')->get();

And then, you can iterate through your results as so:

foreach($attendances as $attendance){
    echo $attendance->member->id;
    echo $attendance->member->name;
}

Upvotes: 1

IndianCoding
IndianCoding

Reputation: 2683

You should use whereHas method with nested relations.

$attendances = Attendance::with('member')
    ->whereHas('member.positions', function($query){
        $query->where('id', 2);
    })
    ->get();

foreach($attendances as $attendance){
    echo $attendance->member->id;
}

Upvotes: 1

Related Questions