简体   繁体   中英

id: null when creating a new item in sequelize

When I try to create a new Conversation item Sequelize will return an object with id: null eventhough there is an valid id in the database. How can I get Sequelize to return the last inserted id to the newly created item?

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

Will return

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

My code:

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 need to put autoIncrement: true in id field

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

Personally i would advice to skip the id column as sequalize does it automatically for you and works nicely.

hope it helps :)

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

I'm not sure about how Sequelize is working with id field, I get null if I do instance.id , bug I can get the real value at DB if I do the following:

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

Something similar is happening with other fields like createdAt and updatedAt .

In order to get the real value at id field and other related fields, I added following logic to Model declaration:

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

because if you only build without save it then: instance.id // null so you need: instance.save() instance.id // someNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM