42

使用 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 添加这些外键约束?

4

5 回答 5

45

在我遇到同样的问题之前,当我了解设置 Sequelize 的功能时解决了。

开门见山!

假设我们有两个对象:PersonFather

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

于 2014-04-12T19:34:47.673 回答
36

对于 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阅读有关关联的更多信息

于 2018-06-14T23:13:52.100 回答
7

您需要添加foreignKeyConstraint: true

尝试:

MainClient.hasOne(MainDashboard, { foreignKey: 'idClient', foreignKeyConstraint: true })
于 2014-01-14T04:49:54.677 回答
6

我只是尝试运行您的代码,并且行似乎创建得很好:

CREATE TABLE IF NOT EXISTS `main_dashboard` (`title` VARCHAR(255), `id` INTEGER NOT NULL auto_increment , `idClient` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `main_client` (`id` INTEGER NOT NULL auto_increment,  `clientId` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;

clientId被添加到main_client,并且idClient被添加到main_dashboard

看来您对该hasOne方法的作用有些困惑。每次调用时hasOne都会创建一个关联,因此您的代码有效地将两个表关联了两次。您正在寻找的方法是belongsTo

如果您希望每个客户都有一个仪表板,代码如下:

MainClient.hasOne(MainDashboard, { foreignKey: 'clientId' })
MainDashboard.belongsTo(MainClient, { foreignKey: 'clientId' })

这会在表上创建一个clientId字段,该字段与表的字段相关main_dashboardidmain_client

In short belongsTo adds the relation to the table that you are calling the method on, hasOne adds it on the table that is given as argument.

于 2013-01-05T20:27:25.980 回答
2

这非常简单。

const MainDashboard = this.sequelize.define('main_dashboard', {/* attributes */}),
      MainClient    = this.sequelize.define('main_client', {/* attributes */});

MainDashboard.belongsTo(MainClient, { foreignKey: 'clientId' }); // Adds clientId to MainDashboard

它会将其链接为外键,您可以将其用作关联。让我知道我是否遗漏了什么。

于 2019-11-13T20:03:12.487 回答