当我尝试创建新的对话项时,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
会自动为您完成并且效果很好。
希望有帮助:)
问题是我的 MySQL 版本(5.6 而不是 5.7),更新了它,现在我得到了承诺中创建的项目的 id。
我不确定 Sequelize 如何与
id
字段一起使用,如果我这样做 null
,我会得到 instance.id
,错误,如果我执行以下操作,我可以在数据库中获得实际值:
console.info(instance.id); // null
console.info(instance.get('id')); // 25 => Real ID
console.info(instance.getDataValue('id')); // 25 => Real ID
类似的事情也发生在其他领域,如
createdAt
和 updatedAt
。
为了获取
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');
}
}
因为如果你只构建而不保存它那么:
instance.id // null
所以你需要:
instance.save()
instance.id // someNumber
为了添加 FastTurtle 的答案,我在 Sequelize 迁移文件中有
autoIncrement: true
,但在模型中没有。
迁移的自动增量正在工作,并且 id 在表中上升,但续集不断返回 null。
一旦我将
autoIncrement: true
添加到模型中,它就为我解决了这个问题。