[英]Flatten Laravel Eloquent Collection relationships
I am using the following database structure: 我使用以下数据库结构:
movie 电影
- id - ID
- title - 标题
director 导向器
- id - ID
- name - 名称
movie_director 电影导演
- director_id - movie_id - director_id - movie_id
The models are set up like this: 模型设置如下:
Movie.php 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 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. 我认为这样做的一种方法是使用
hasManyThrough
为Movie
模型添加一个方法,以获取导演相关的其他电影。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.