Sequelize:如何在数据透视表中映射自定义属性

Luc*_*bou 6 mysql node.js sequelize.js

我有这个数据透视表,它代表了人物和电影模型的多对多关系.

数据透视表模式

事情是,当我打电话给那些让人联系起来的电影时,我希望得到这个角色.我尝试了这个,但它没有显示角色:

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

我是否必须在模型中指定一些内容role

Luc*_*bou 5

我终于通过movie_person使用role属性作为字符串创建数据透视表的模型来实现此目的.

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

然后在我的Movie模型中我添加了这个

Movie.belongsToMany(models.Person, {
    through: models.MoviePerson,
    foreignKey: 'movie_id',
    as: 'persons'
});
Run Code Online (Sandbox Code Playgroud)

我必须在我的Person模型中做一些与此类似的事情,就是这样!