Search code examples
phpmysqleloquentlaravel-5relationships

Laravel Pivot table eloquent relationships


Situation: In my laravel project. Below are the 4 Tables. movie_venue is a pivot table of movies and venues. I need to access the showtimes using movie model.

$movie = $this->model->find($movie_id);

$venues = $movie->venues;

Using eloquent relations i can access the venues list. But cant able to create a relationship for getting showtimes from movie model.


| movies     | venues | movie_venue | showtimes     |
----------------------------------------------------|
| id         | id     | id          |id             |
| name       | name   | movie_id    |movie_venue_id |
| ....       |  ....  | venue_id    |time           |

Solution

  • I assume you're using a One-to-many relationship for Venues to Showtimes?

    You could try something like:

    foreach ($movies->venues as $venue) {
        foreach ($venue->showtimes as $showtime) {
            //do something with your showtime.
        }
    }
    

    By the way: wouldn't it make more sense to start from the venue and than access Showtimes?

    UPDATE

    Based on your comment, you can try something like this:

    $movie = Movie::find($id);
    $venues = $movie->venues;
    
    foreach ($venues->showtimes as $showtime) {
        // Here you'll get the showtimes per venue.
    }