mercredi 26 avril 2017

Many to Many laravel

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire