id:在续集中创建新项目时为空

id: null when creating a new item in sequelize

本文关键字:新项目 创建 集中 id      更新时间:2023-09-26

当我尝试创建新的对话项目时,即使数据库中有一个有效的id,Sequelize也会返回一个带有id: null的对象。如何让续集将上次插入的 id 返回给新创建的项目?

Conversation.create({
  type: 'private',
  createdBy: 1,
}).then(conversation => {
  reply(conversation);
});

会回来

{
  "type": "conversations",
  "id": null,
  "createdBy": 1,
  "created_at": "2016-03-18T01:47:48.000Z"
}

我的代码:

const Conversation = model.define('Conversation', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  type: {
    type: Sequelize.ENUM,
    values: ['private', 'group'],
    validate: {
      isIn: ['private', 'group'],
    },
  },
  createdBy: {
    type: Sequelize.INTEGER,
    field: 'created_by',
  },
}, {
  tableName: 'conversations',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: false,
  getterMethods: {
    type: () => 'conversations',
  },
});
const User = model.define('User', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  firstName: {
    type: Sequelize.STRING,
    field: 'first_name',
    allowNull: false,
  },
  lastName: {
    type: Sequelize.STRING,
    field: 'last_name',
    allowNull: true,
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  profileImg: {
    type: Sequelize.STRING,
    field: 'profile_img',
    allowNull: false,
  },
  password: Sequelize.STRING,
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  getterMethods: {
    type: () => 'users',
  },
});
Conversation.belongsToMany(User, {
  foreignKey: 'conversation_id',
  otherKey: 'user_id',
  through: 'conversation_user',
  timestamps: false,
});
User.belongsToMany(Conversation, {
  as: 'conversations',
  foreignKey: 'user_id',
  otherKey: 'conversation_id',
  through: 'conversation_user',
  timestamps: false,
});

Yo 需要将autoIncrement: true放在id字段中:

id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  }

就个人而言,我建议跳过idsequalize因为它会自动为您完成并且效果很好。

希望对:)有所帮助

问题是我的 MySQL 版本(5.6 而不是 5.7),更新了它,现在我在承诺中获得了所创建项目的 id。

我不确定 Sequelize 如何处理id字段,如果我这样做,我会null instance.id,如果我执行以下操作,我可以在 DB 获得真正的价值:

console.info(instance.id); // null
console.info(instance.get('id')); // 25 => Real ID
console.info(instance.getDataValue('id')); // 25 => Real ID

类似的事情也发生在其他领域,如createdAtupdatedAt .

为了获取id字段和其他相关字段的实际值,我在模型声明中添加了以下逻辑:

class FooModel extends Model {
  // ...
  /**
   * @inheritdoc
   */
  public async save(options?: SaveOptions<TModelAttributes>): Promise<this> {
    await super.save(options);
    this.loadBaseData();
    return this;
  }
  /**
   * @inheritdoc
   */
  public async reload(options?: FindOptions<TModelAttributes>): Promise<this> {
    await super.reload(options);
    this.loadBaseData();
    return this;
  }
  private loadBaseData() {
    this.id = this.getDataValue('id');
    this.createdAt = this.getDataValue('createdAt');
    this.updatedAt = this.getDataValue('updatedAt');
  }
}

因为如果你只构建而不保存它,那么:

instance.id // null

所以你需要:

instance.save()
instance.id // someNumber