gpt4 book ai didi

php - 扁平化 Laravel Eloquent Collection 关系

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:17 25 4
gpt4 key购买 nike

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

电影
- 编号
- 标题

导演
- 编号
- 姓名

电影导演
- director_id- 电影编号

模型是这样设置的:

电影.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);

关于php - 扁平化 Laravel Eloquent Collection 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43392144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com