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

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波