Llo*_*oyd 5 php collections flatten laravel eloquent
我正在使用以下数据库结构:
电影
-ID-
标题
导演
-身份证
-姓名
movie_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');
}
}
Run Code Online (Sandbox Code Playgroud)
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');
}
}
Run Code Online (Sandbox Code Playgroud)
因此,电影和导演之间存在多对多的关系。
我想在电影的详细信息页面上张贴原始电影导演的其他电影。
$movie = Movie::with('directors.movies')->find(1);
Run Code Online (Sandbox Code Playgroud)
这给了我所有我需要的数据,但是要获得电影的完整列表,我必须遍历Directors集合,然后遍历该Director内部的电影集合。难道没有更快/更容易的方法吗?
我认为做到这一点的一种方法是在Movie模型中添加一种方法,用于hasManyThrough获取导演相关的其他电影。
public function relatedMovies()
{
return $this->hasManyThrough('App\Movie', 'App\Director');
}
Run Code Online (Sandbox Code Playgroud)
然后单独急切加载该关系,而不是急切加载嵌套关系。
$movie = Movie::with('directors', 'relatedMovies')->find(1);
Run Code Online (Sandbox Code Playgroud)