[英]Flatten Laravel Eloquent Collection relationships
我使用以下数据库结构:
电影
- ID
- 标题
导向器
- ID
- 名称
电影导演
- 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');
}
}
因此,电影和导演之间存在多对多的关系。
在电影的详细页面上,我想发布原始电影导演的其他电影。
$movie = Movie::with('directors.movies')->find(1);
这给了我所需的所有数据,但要获得完整的电影列表,我必须循环遍历导演集合,然后循环播放导演中的电影集。 是不是有更快/更简单的方法来做到这一点?
我认为这样做的一种方法是使用hasManyThrough
为Movie
模型添加一个方法,以获取导演相关的其他电影。
public function relatedMovies()
{
return $this->hasManyThrough('App\Movie', 'App\Director');
}
然后分别急切加载那个关系,而不是急于加载嵌套关系。
$movie = Movie::with('directors', 'relatedMovies')->find(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.