gpt4 book ai didi

javascript - 编号 : null when creating a new item in sequelize

转载 作者:搜寻专家 更新时间:2023-11-01 00:14:30 27 4
gpt4 key购买 nike

当我尝试创建一个新的对话项时,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,
});

最佳答案

你需要把 autoIncrement: true 放在 id 字段中:

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

我个人建议跳过 id 列,因为 sequalize 会自动为您完成,并且效果很好。

希望对你有帮助:)

关于javascript - 编号 : null when creating a new item in sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074800/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com