【发布时间】:2017-09-09 13:39:02
【问题描述】:
我正在使用以下数据库结构:
电影
- 身份证
- 标题
导演
- 身份证
- 名称
电影导演
-director_id
- movie_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');
}
}
导演.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);
这为我提供了我需要的所有数据,但要获得完整的电影列表,我必须遍历导演集合,然后遍历导演内部的电影集合。没有更快/更简单的方法吗?
【问题讨论】:
-
也许我遗漏了一些东西,但你不能按照laravel.com/docs/5.4/collections#available-methods 对它使用 flatten 或 flatMap 吗?
-
是的,我可以这样做:
$movies = $movie->directors->flatMap(function ($val) {return $val->movies; });但是如果您需要更上一层楼,或者更深两层怎么办?然后你需要嵌套多个这些 flatMap 函数。我真的希望有一种更简单的方法,例如使用点符号。
标签: php laravel collections eloquent flatten