id: 在 sequelize 中创建新项目时为 null [英] id: null when creating a new item in sequelize

查看:61
本文介绍了id: 在 sequelize 中创建新项目时为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

会回来

{
  "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,
});

推荐答案

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

Problem was my MySQL version (5.6 instead of 5.7), updated it and now I'm getting id's of the created items in the promise.

这篇关于id: 在 sequelize 中创建新项目时为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆