Sequelize doesn't create foreign keys as constraints

前端 未结 1 899
一个人的身影
一个人的身影 2021-01-07 07:15

We\'re trying to create tables automatically inside PostgreSQL using Sequelize. Unfortunately, it doesn\'t create the foreign keys as constraints. Here is an example of one

相关标签:
1条回答
  • 2021-01-07 07:35

    First, it's not uncommon for ORMs to handle this kind of thing internally rather than by using foreign key constraints in the database.

    Second, it's not uncommon for ORMs to require a pair of association statements to trigger all the internal handling you might expect.

    var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
      , User = this.sequelize.define('User', { username: Sequelize.STRING })
    
    User.hasMany(Task)
    Task.belongsTo(User)
    

    Finally, Sequelize will actually write foreign key declarations into the database, but only if you also declare some kind of action (or inaction) with onUpdate or onDelete.

    To add references constraints to the columns, you can pass the options onUpdate and onDelete to the association calls. . . .

    User.hasMany(Task, { onDelete: 'SET NULL', onUpdate: 'CASCADE' })
    
    CREATE TABLE IF NOT EXISTS `Task` (
      `id` INTEGER PRIMARY KEY, 
      `title` VARCHAR(255), 
      `user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
    );
    

    Code example source

    0 讨论(0)
提交回复
热议问题