duanhe6718 2017-04-13 12:17
浏览 31
已采纳

Flatten Laravel Eloquent Collection关系

I am using the following database structure:

movie
   - id
   - title

director
   - id
   - name

movie_director
   - director_id    - movie_id

The models are set up like this:

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');
    }
}

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?

  • 写回答

1条回答 默认 最新

  • duanlu6114 2017-04-14 21:42
    关注

    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.

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?