简体   繁体   中英

Flatten Laravel Eloquent Collection relationships

I am using the following database structure:

movie
- id
- title

director
- id
- name

movie_director
- director_id - movie_id

The models are set up like this:

Movie.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
    public $table = "movie";

    /**
     * The roles that belong to the user.
     */
    public function directors()
    {
        return $this->belongsToMany('App\Director', 'movie_director');
    }
}

Director.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Director extends Model
{
    public $table = "director";

    /**
     * The roles that belong to the user.
     */
    public function movies()
    {
        return $this->belongsToMany('App\Movie', 'movie_director');
    }
}

So there is a many-to-many relationship between a movie and a director.

On the detail page of a movie I would like to post other movies of the directors of the original movie.

    $movie = Movie::with('directors.movies')->find(1);

That gives me all the data I need, but to get a complete list of movies I would have to loop through the directors collection and then loop through the movies collection inside that director. Isn't there a faster/easier way to do this?

I think one way to do this would be to add a method to your Movie model using hasManyThrough to get the other movies related by director.

public function relatedMovies()
{
    return $this->hasManyThrough('App\Movie', 'App\Director');
}

Then separately eager load that relationship, rather than eager loading the nested relationship.

$movie = Movie::with('directors', 'relatedMovies')->find(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM