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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号