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

Viewed 7392

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 ?

2 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 !

For the purpose of those who will need this, there is a new method called 'magic methods'. I believe you have declared your many-to-many asociation


    const movies = Movie.findAll();
    const person = Person.findbyPk(personId);
    const moviesPerson = movies.getPersons(person);

Related