3

假设最简单的例子:

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

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

如果我们sequelize.sync这样做,我们会得到一个ChildrenPersons连接表,它有一个由PersonIdand组成的两列主键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

我如何制作PersonIdChildrenId CONSTRAIN编辑外键,引用Persons.id

我尝试手动创建连接表,但没有奏效。

4

1 回答 1

2

我对 sequelize 不是很熟悉,但我知道您可以使用它直接发出 SQL 查询和命令sequelize.query

因此,如果您只想创建具有外键约束的两个表,这里是适当的 SQL(请注意,这是 SQLite 方言 - 注意缺少日期时间)

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 (Confirmed to be working with 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

于 2014-08-17T07:30:01.233 回答