【问题标题】:nodejs sequelize: I can't update the primary key field's valuenodejs sequelize:我无法更新主键字段的值
【发布时间】:2018-11-28 21:07:48
【问题描述】:

我可以更新除 id(主键)之外的每个字段的值。这是一个网站。我希望能够通过网站更新 id。

module.exports = {
schema: function (sequelize, DataTypes) {
    return sequelize.define(
        'T_Event',
        {
            id: {
                type: DataTypes.STRING,
                primaryKey: true
            },
            user_id: {
                type: DataTypes.STRING
            },
            name: {
                type: DataTypes.STRING
            },
            created_at: {
                type: DataTypes.DATE
            },
            description: {
                type: DataTypes.STRING
            },
            image: {
                type: DataTypes.STRING
            },
            closed_at: {
                type: DataTypes.DATE
            }
        },
        {
            timestamps: true,
            paranoid: true,
            underscored: true,
            freezeTableName: true
        }
    )
}

我正在使用带有节点和 MySQL 数据库的 sequelize 3.33.0。 所有属性都具有选择、插入和更新权限。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    出于安全原因,Sequelize 会限制此类操作。通常通过运行时使用用户提供的信息更新主键是一个坏主意。这可能会导致各种问题,尤其是当更改的对象正在被其他用户使用时。

    我遵循经验法则:如果列值可以更改,则它不适合作为主键。如果所有列中都没有合适的候选者,请创建一个仅用于此目的的候选者。

    schema: function (sequelize, DataTypes) {
        return sequelize.define(
            'T_Event',
            {
                uid: {
                    type: DataTypes.BIGINT,
                    primaryKey: true,
                    autoIncrement: true
                },
                id: {
                    type: DataTypes.STRING,
                    unique: true
                },
                // ...
        )
    }
    

    也就是说,在某些情况下这种解决方案是不可行的。在这种情况下,您可以使用变通方法,进行更改 id 的更新:

    T_Event.update(
        {
            id: new_value
        }, {
            where: {
                uid: current_value
            }
        }
    );
    

    【讨论】:

    • 超级!我创建了一个新专栏来解决这个问题并得到了我想要的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多