I have 3 tables for my site (laravel 4.2)
- events
- bands
- artists
and 1 pivot table
event_band_artist
| event_id | band_id | artist_id |
| --------- | ------- | --------- |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 3 |
Event Model
public function bands() {
return $this->belongsToMany('Band', 'event_band_artist');
}
public function artists() {
return $this->belongsToMany('Artist', 'event_band_artist');
}
Band Model
public function events() {
return $this->belongsToMany('Event', 'event_band_artist');
}
public function artists() {
return $this->belongsToMany('Artist', 'event_band_artist');
}
Artist Model
public function events() {
return $this->belongsToMany('Event', 'event_band_artist');
}
public function bands() {
return $this->belongsToMany('Band, 'event_band_artist');
}
Controller
$events = Event::find($id);
return View::make('event')->with('events', $events);
View
<h3>{{ $events->name }}</h3>
<ul>
@foreach ($events->bands as $band)
<li>{{ $band->name }}</li>
</ul>
@endforeach
Which results
Event I
My problem here is that foreach is retrieving Band A (band_id = 1) twice, because the pivot table contains 2 records of the same Band for the Event 1.
But in this case, I am repeating the Band 2x because it has 2 different artists, as you can in the table at the top of this post.
That is, an artist can belongs to more than one Band, depending on the Event.
So what I want to know is how to retrieve Bands filtered by the event_id, so that the same Band will not load more than one time in the View page.
Or should I think at another kind of relationship among these 3 tables?
Thanks for your time.
Alex