Many to Many laravel

Brian

I have the following situation: The database table "Movies" has a many to many relation with "Actors"

This is the relation image

Now I need to get all the movies that have the actors with for example ID 1, 8, 20

How can I do this with the query builder from 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);
    }
}

I am trying it like above, but that doesn't work.

Leguam
// 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;
    }
}

Laravel official docs reference

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related