如何在自引用关联中强制执行外键约束?

时间:2013-10-30 14:47:58

标签: node.js sequelize.js

假设最简单的例子:

var Person = sequelize.define('Person', {
  name: Sequelize.STRING,
});

Person.hasMany(Person, { as: 'Children', foreignKeyConstraint: true });

如果我们sequelize.sync这个,我们会得到一个ChildrenPersons连接表,它有一个由PersonIdChildrenId组成的双列主键,但没有外键:

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

如何引用PersonIdChildrenId CONSTRAIN个外键,引用Persons.id

我尝试了manually creating the join table,但它没有用。

1 个答案:

答案 0 :(得分:2)

我对sequelize并不熟悉,但我知道你可以用sequelize.query

直接发出SQL查询和命令

所以如果你只想创建带有外键约束的两个表,这里是相应的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