假设最简单的例子:
var Person = sequelize.define('Person', {
name: Sequelize.STRING,
});
Person.hasMany(Person, { as: 'Children', foreignKeyConstraint: true });
如果我们sequelize.sync
这个,我们会得到一个ChildrenPersons
连接表,它有一个由PersonId
和ChildrenId
组成的双列主键,但没有外键:
CREATE TABLE `ChildrenPersons` (
`PersonId` int(11) NOT NULL DEFAULT '0',
`ChildrenId` int(11) NOT NULL DEFAULT '0',
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`PersonId`,`ChildrenId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
如何引用PersonId
和ChildrenId
CONSTRAIN
个外键,引用Persons.id
?
我尝试了manually creating the join table,但它没有用。
答案 0 :(得分:2)
我对sequelize并不熟悉,但我知道你可以用sequelize.query
所以如果你只想创建带有外键约束的两个表,这里是相应的SQL(请注意这是SQLite方言 - 注意缺少datetime)
CREATE TABLE Persons(
id integer primary key,
name text);
CREATE TABLE ChildrenPersons(
personId integer not null,
childrenId integer not null,
createdAt integer not null,
updatedAt integer not null,
primary key(personId,childrenId),
foreign key(personId) references Persons(id),
foreign key(childrenId) references Persons(id));
我希望这会有所帮助
修改强>
以下代码将使用sequelize lingo创建表(已确认将使用sequelize 1.7.9):
var Sequelize = require('sequelize'),
sequelize = new Sequelize('test','','',
{
dialect: 'sqlite',
storage: 'test.db'
})
var Person = sequelize.define('Person', {name: Sequelize.STRING})
var PersonChildren = sequelize.define('PersonChildren',
{
PersonId: {
type: Sequelize.INTEGER,
references: Person,
referencesKey: 'id',
primaryKey: true
},
ChildrenId: {
type: Sequelize.INTEGER,
references: Person,
referencesKey: 'id',
primaryKey: true
}
})
sequelize.sync({force: true}).complete(function(err){
if(!!err){
console.log('Error: ',err)
}else
{
console.log('All OK')
}
})
请关注Sequelize文档文章,以强制执行外键约束: http://sequelizejs.com/docs/latest/associations