我想在offeret表中添加offerzone表作为外键。使用sequelize和以下模型是用angularjs编写的。
module.exports = function(sequelize, DataTypes) {
let offerzone = sequelize.define('offerzone', {
title: DataTypes.STRING,
moid: DataTypes.INTEGER,
seoTandC: DataTypes.STRING,
isActive: DataTypes.BOOLEAN,
set: DataTypes.ARRAY(DataTypes.STRING),
isDeleted: DataTypes.BOOLEAN
}, {
classMethods: {
associate: function(models) {
offerzone.belongsToMany(models.offerset, {
through: 'models.offerset'
foreign-key: 'offerzone'
as: 'offerset'
});
// associations can be defined here
}
}
});
return offerzone;
};
答案 0 :(得分:0)
要在sequelize中定义hasMany关联,如果您想拥有例如Videos hasMany Comments,则以下步骤如下。
在视频中,您将拥有类似视频模型
的内容module.exports = function (sequelize, DataTypes) {
var Video = sequelize.define("Video", {
author: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
Video.hasMany(models.Comment, {foreignKey: 'videoid', onDelete: 'cascade', hooks: true});
}
}
});
return Video;
};
评论模型将是:
module.exports = function (sequelize, DataTypes) {
var Comment = sequelize.define("Comment", {
commentary: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
Comment.belongsTo(models.Video, {foreignKey: 'videoid', allowNull: false});
}
}
});
return Comment;
};
部分onDelete: 'cascade', hooks: true
表示如果删除视频,评论也会被删除