拉平 Laravel Eloquent Collection 关系

Flatten Laravel Eloquent Collection relationships

我正在使用以下数据库结构:

电影
- 编号
- 标题

导演
- 编号
- 姓名

movie_director
- director_id - movie_id

模型设置如下:

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

所以电影和导演之间存在many-to-many关系。

在一部电影的详情页面我想post原电影导演的其他电影。

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

这为我提供了我需要的所有数据,但要获得完整的电影列表,我必须循环遍历导演 collection,然后循环遍历该导演中的电影 collection。没有 faster/easier 的方法吗?

我认为一种方法是使用 hasManyThrough 向您的 Movie 模型添加一种方法,以获取导演相关的其他电影。

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

然后分别预先加载该关系,而不是预先加载嵌套关系。

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