使用belongsToMany
关联时,Sequelize将add
方法附加到每个隐含模型。例如,让我们有下图:
这可以使用Sequelize中的以下模型来实现:
// SHOP
const Shop = sequelize.define('Shop', {
name: DataTypes.STRING
});
Shop.associate = function(models) {
Shop.belongsToMany(models.Employee, {through: 'ShopEmployee'});
};
// EMPLOYEES
const Employee = sequelize.define('Employee', {
name: DataTypes.STRING,
DOB: DataTypes.DATE
});
Employee.associate = function(models) {
Employee.belongsToMany(models.Shop, {through: 'ShopEmployee'});
};
// N:M RELATIONSHIP TABLE
const ShopEmployee = sequelize.define('ShopEmployee', {
schedule: DataTypes.STRING
});
一旦我们创建了一些商店和员工,就可以使用自动附加的addEmployee
方法将员工添加到商店:
// 'shop' and 'employee' are model instances
shop.addEmployee(employee, { through: { schedule: '06:00-10:00' } })
Sequelize还生成一个addEmployees
方法,该方法接受实例数组或带有要添加的员工ID的数组,因此我可以这样做:
// employees is an array of Employee instances
shop.addEmployees(employees);
shop.addEmployees([3, 4, 7, 8]);
这可以正常工作,但是没有在表schedule
中设置ShopEmployee
属性。是否可以使用through
为每个数组项指定一个值?这不起作用:
shop.addEmployees([3, 4, 7, 8], { through: [ '6-10', '10-12', '12-15', '15-18' ] });
它正确地添加了4名员工,但为每个员工分配了相同的时间表(“ 6-10”)。
有什么建议吗?谢谢!