Larger relationship Laravel Eloquent Collection

I use the following database structure:

movie
    - id
    - title

director
    - id
    - name

movie_director
    - Director_id - movie_id

Models are configured as follows:

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');
    }
}

Thus, there is a many-to-many relationship between the film and the director.

On the detailed page of the film, I would like to place other films directed by the original film.

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

This gives me all the data I need, but in order to get a complete list of films, I would have to go through the collection of directors, and then scroll through the collection of films inside that director. Is there a faster / easier way to do this?

+4
1

, Movie, hasManyThrough, , .

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

, .

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

Source: https://habr.com/ru/post/1674746/


All Articles