表客户:
const Customer=sequelize.define('Customer', {
id_customer: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING(128),
allowNull: false
}
// Class Method
Customer.associate = function (models) {
Customer.belongsToMany(models.Group, {
through :models.CustomerGroup,
foreignKey: 'id_customer'
});
};
CustomerGoup表
const CustomerGroup = sequelize.define('CustomerGroup', {
id_customer: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true
},
id_group: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true
}
}
小组表:
module.exports = function(sequelize, DataTypes) {
const Group = sequelize.define('Group', {
id_group: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
reduction: {
type: DataTypes.DECIMAL,
allowNull: false,
defaultValue: '0.00'
},
price_display_method: {
type: DataTypes.INTEGER(4),
allowNull: false,
defaultValue: '0'
},
show_prices: {
type: DataTypes.INTEGER(1).UNSIGNED,
allowNull: false,
defaultValue: '1'
},
date_add: {
type: DataTypes.DATE,
allowNull: false
},
date_upd: {
type: DataTypes.DATE,
allowNull: false
}
}
// Class Method
Group.associate = function (models) {
Group.belongsToMany(models.Customer, {
through :models.CustomerGroup,
foreignKey: 'id_group'
});
};
现在我正在尝试将客户保存到 Customer 表中。然后我需要创建一个连接客户和组的记录。所以我需要在表 CustomerGroup 中创建一条记录。 我的代码如下:
let newCustomer = db.Customer.build({
email:email,
group: [
{id_group: 1}
]
},{
assoication: [{
model:db.Group,
as:'group'
}]
});
作为我的代码,我保存了客户信息。但得到错误Unhandled rejection Error: Group (group) is not associated to Customer!
有人可以告诉我我的代码有什么问题吗?感谢