【问题标题】:Sequelize relations foreign key constraintSequelize 关系外键约束
【发布时间】:2020-03-17 21:49:58
【问题描述】:

我有一个使用 sequelize create 方法将事件添加到数据库的发布路线。我已经为用户和事件定义了表:

活动

    const Events = sequelize.define('Events', {
        Event_id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
          },
          name: {
            type: DataTypes.STRING,
            allowNull: false
          },
          month: {
            type: DataTypes.STRING,
            allowNull: false
          },
          day:{
            type:DataTypes.INTEGER,
            allowNull: false
          },
          year: {
            type: DataTypes.INTEGER,
            allowNull: false
          },
          important:{
              type: DataTypes.BOOLEAN,
              allowNull: false,
              defaultValue: false
          },
          description:{
              type: DataTypes.STRING,
              allowNull: true
          }
    });
    return Events;
}

用户

    const User = sequelize.define('Users', {
        user_id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
          },
          name: {
            type: DataTypes.STRING,
            allowNull: false
          },
          email: {
            type: DataTypes.STRING,
            allowNull: false
          },
          password: {
            type: DataTypes.STRING,
            allowNull: false
          }
    }, {});
    User.associate = function(models){
      User.hasMany(models.Events, {as: 'user'})
    }
    return User;
}

post 路由似乎运行正常,除了 sequelize 无法将用户 ID 附加到创建的事件做到

"无法添加或更新子行:外键约束失败 (planitdb.events, CONSTRAINT events_ibfk_1 FOREIGN KEY (UserUserId) REFERENCES users (user_id) ON DELETE SET NULL更新级联)"

我不确定我是否完全理解为什么会发生这种情况。我想我还需要在事件表中定义关系吗?如果是这种情况,我不确定我是否了解 Events 表与 User 表之间的关系类型。或者这种关系是对单个用户的单个事件?

任何帮助将不胜感激。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    您的事件对象不包含 user_id 的映射。该对象需要包含一个 user_id 字段,并且需要在尝试将记录插入事件表之前填充该字段。

    编辑 - 包括续集关系解决方案:

    而不是这个:

    const Events = sequelize.define('Events', {...});
    User.associate = function(models){
      User.hasMany(models.Events, {as: 'user'})
    }
    

    试试:

    const Events = sequelize.define('Events', {...});
    const User = sequelize.define('User', {...});
    User.hasMany(Events, {as: 'user'});
    

    或:

    const Events = sequelize.define('Events', {});
    const User = sequelize.define('User', {...});
    Events.belongsTo(User,{
        foreignKey: 'user_id',
        constraints: false,
        as: 'user'
    });
    

    【讨论】:

    • 我的印象是我会通过续集关系来做这件事,但为此它应该按照你描述的方式工作。
    • 就像任何事情一样,有很多方法可以实现相同的结果。您可以(并且可能应该)使用 sequelize 关系来完成此操作。最后我没有看到 hasMany 关系。您应该尝试在事件实体上使用 belongsTo。如我所提到的,belongsTo 或手动定义字段应该可以让您到达那里。
    猜你喜欢
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2018-02-13
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多