在使用Sequelize.js时,以下代码不会在表中添加任何外键。
var MainDashboard = sequelize.define('main_dashboard', {
title: Sequelize.STRING
}, {
freezeTableName: true
})
MainClient.hasOne(MainDashboard, { foreignKey: 'idClient' })
MainDashboard.hasOne(MainClient, { foreignKey: 'clientId' })
sequelize.sync({ force: true })有没有办法强制Sequelize.js添加这些外键约束?
发布于 2014-04-13 03:34:48
之前我也有过同样的问题,当我了解了设置的功能后解决了续订。
开门见山吧!
假设我们有两个对象:Person和
var Person = sequelize.define('Person', {
name: Sequelize.STRING
});
var Father = sequelize.define('Father', {
age: Sequelize.STRING,
//The magic start here
personId: {
type: Sequelize.INTEGER,
references: 'persons', // <<< Note, its table's name, not object name
referencesKey: 'id' // <<< Note, its a column name
}
});
Person.hasMany(Father); // Set one to many relationship也许这对你有帮助
编辑:
你可以阅读这篇文章来更好地理解:
http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys
发布于 2018-06-15 07:13:52
对于Sequelize 4,这已更新为以下内容:
const Father = sequelize.define('Father', {
name: Sequelize.STRING
});
const Child = sequelize.define('Child', {
age: Sequelize.STRING,
fatherId: {
type: Sequelize.INTEGER,
references: {
model: 'fathers', // 'fathers' refers to table name
key: 'id', // 'id' refers to column name in fathers table
}
}
});
Father.hasMany(Child); // Set one to many relationship编辑:您可以在https://sequelize.org/master/manual/assocs.html上阅读有关关联的更多信息
发布于 2014-01-14 12:49:55
您需要添加foreignKeyConstraint: true
尝试:
MainClient.hasOne(MainDashboard, { foreignKey: 'idClient', foreignKeyConstraint: true })https://stackoverflow.com/questions/14169655
复制相似问题