Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize : How to map a custom attribute in a pivot table

I've got this pivot table, which represents a many to many relationship with the models Person and Movie.

Pivot table schema

The thing is I want to get the role when I call the movies that get the persons associated. I tried this but it doesn't show the role :

models.Movie.findAll({
    include: [{
        model: models.Person,
        as: 'persons',
        through: {attributes: ["role"]}
    }]
}).then(function(movies) {
    res.json(movies);
});

Do I have to specify something in the models for the role ?

like image 478
Lucaribou Avatar asked Mar 25 '16 07:03

Lucaribou


1 Answers

I finally managed to achieve this by creating a model for the pivot table movie_person with the role attribute as a string.

var MoviePerson = sequelize.define("MoviePerson", {
    role: DataTypes.STRING
},
{
    tableName: 'movie_person',
    underscored: true
});

Then in my Movie model I added this

Movie.belongsToMany(models.Person, {
    through: models.MoviePerson,
    foreignKey: 'movie_id',
    as: 'persons'
});

I had to do something obviously similar to this in my Person model and that's it !

like image 129
Lucaribou Avatar answered Oct 19 '22 10:10

Lucaribou