postgresql - Sequelize 不会创建外键作为约束

标签 postgresql sequelize.js

我们正在尝试使用 Sequelize 在 PostgreSQL 中自动创建表。不幸的是,它不会创建外键作为约束。这是我的一个模型的示例:

module.exports = function(schema, DataTypes) {

    var definition = {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        deal_id: {
            type: DataTypes.INTEGER
        },
        image: DataTypes.STRING,
    };


    var image = schema.define('Image', definition, {
        tableName: 'images', // this will define the table's name
        timestamps: false, // this will deactivate the timestamp columns
        syncOnAssociation: true,

        classMethods: {
            getDefinition: function() {
                return definition;
            },
            associate: function(_models) {
                image.belongsTo(_models.Product, {
                    foreignKey: 'deal_id'
                });
            }
        }
    });

    return image;
};

我做错了什么吗?

最佳答案

首先,ORM 在内部处理此类事情而不是在数据库中使用外键约束并不少见。

其次,ORM 要求一对 关联语句来触发您可能期望的所有内部处理的情况并不少见。

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

User.hasMany(Task)
Task.belongsTo(User)

最后,Sequelize 实际上会将外键声明写入数据库,但前提是您还使用 onUpdateonDelete 声明了某种 Action (或不 Action )。

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

关于postgresql - Sequelize 不会创建外键作为约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26421713/

相关文章:

Node.js Sequelize 依赖问题

postgresql - 如何将 varchar 转换为 bool postgresql

c# - 如何连接到由模式分隔的 postgresql 数据库?

sql - 如果使用 where 子句时数据为空,则将数据计为零

node.js - sequelize-auto 找不到模块 'sequelize'

node.js - 如何使用 Server.inject 注入(inject)模拟测试 hapi

带有 sequelize 和 Node js 的 Mysql native 空间函数

mysql - 使用 sequelize 从 child 那里获取父记录

postgresql - 非英语语言的 en_us.UTF8 归类

sql - 如何更正此查询中具有相同日期的某些参数 Order by date 的分区?