Php 多对多拉威尔

Php 多对多拉威尔,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我有以下情况: 数据库表“Movies”与“Actors”有多对多关系 现在我需要得到所有演员ID为1、8、20的电影 如何使用Laravel 5.4中的查询生成器实现这一点 class Movie extends Model { public function actors(){ return $this->belongsToMany('App\Models\Actor', 'movies_has_actors', 'movie_id', 'actor_id'

我有以下情况: 数据库表“Movies”与“Actors”有多对多关系

现在我需要得到所有演员ID为1、8、20的电影

如何使用Laravel 5.4中的查询生成器实现这一点

class Movie extends Model
{
    public function actors(){
         return $this->belongsToMany('App\Models\Actor', 'movies_has_actors', 'movie_id', 'actor_id');
    }
}

class User extends Authenticatable
{
    public function actors()
    {
        return $this->belongsToMany('App\Models\Actor', 'users_has_actors', 'user_id', 'actor_id')->withPivot('rating', 'favorite')->wherePivot('user_id', $this->id);
    }
    public function functionName(){
        $actor_ids = $this->actors()->where('users_has_actors.rating', '>=', 8)->pluck('id');
        $movie_model = new Movie();
        $movies = $movie_model->actors()->wherePivotIn('actor_id', $actor_ids);
    }
}
我正试着像上面那样,但那不起作用

 $movies = $movie_model->actors()->whereIn('id', $actor_ids);

此操作不返回结果:(此foreach仅返回1名演员的电影对吗?使用(多部)的(多部)电影编辑了我的答案)演员也是。好的,我认为这是正确的方向,除了我将电影作为轴,我不知道如何调用它。$actor->movies返回null,但当我回显结果时,我看到轴中的电影。
// Get actor where id is equal to $id, and eager load movies.
$actor = Actor::where('id', '=', $actor_id)->with('movies')->get();


// If you want to get actors with an array of IDs (with your example IDs)
$actors = Actor::whereIn('id', [1, 8, 20])->with('movies')->get();


// With the returned collection ($actor) you can reach the movies (for example loop through them)
foreach ($actor->movies as $movie) {
    echo $movie->title;
}

// If you want to reach the movies from the $actors collection
// Loop through the actors
foreach ($actors as $actor) {
    // Loop through every movie of the current looped actor
    foreach ($actor->movies as $movie) {
        echo $movie->title;
    }
}