javascript id:在sequelize中创建新项目时为null

ozxc1zmp  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(135)

当我尝试创建一个新的对话项目时,Sequelize将返回一个带有id: null的对象,即使数据库中有一个有效的id。我如何让Sequelize返回最后插入的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,
});
ee7vknir

ee7vknir1#

您需要将autoIncrement: true放入id字段:

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

就我个人而言,我建议跳过id列,因为sequalize会自动为您执行此操作,并且效果很好。
希望对你有帮助:)

iibxawm4

iibxawm42#

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

unguejic

unguejic3#

我不确定 Sequelize 是如何处理id字段的,如果我执行instance.id,我会得到null,如果我执行以下操作,我可以在DB中得到真实的值:

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

类似的事情也发生在其他领域,如createdAtupdatedAt
为了获得id字段和其他相关字段的真实的值,我在 Model 声明中添加了以下逻辑:

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');
  }
}
3bygqnnd

3bygqnnd4#

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

instance.id // null

因此您需要:

instance.save()
instance.id // someNumber

相关问题