【发布时间】:2021-10-04 20:30:01
【问题描述】:
试图让 sequelize 返回具有现有关联的新创建对象。我的目标是创建一个与现有组织相关联的新用户并返回两者。
在 user.model.js:
export default (sequelize, DataTypes) => {
const User = sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: true,
},
});
User.associate = (models) => {
User.belongsTo(models.Organisation, {
foreignKey: {
name: 'organisationId',
field: 'organisation_id',
},
});
};
return User;
};
在 organisation.model.js:
export default (sequelize, DataTypes) => {
const Organisation = sequelize.define('organisation', {
name: {
type: DataTypes.STRING,
unique: true,
},
});
return Organisation;
};
成功:获得现有用户
我可以使用查询的include 选项检索现有用户及其组织。
const user = models.User.findOne({
where: {
email: 'existing@user.com',
},
include: [
{ model: models.Organisation, attributes: ['name'] },
],
});
失败:创建新用户
实例已插入,但查询未能返回组织属性。
const user = models.User.create({
email: 'new@user.com',
organisationId: 'existing-organisation-id'
}, {
include: [
{ model: models.Organisation, attributes: ['name'] },
],
});
成功:创建一个新用户并查询它
插入实例,然后使用通过组织数据检索到的另一个查询。问题是它需要对数据库进行两次查询。它应该只需要一个,
models.User.create({
email: 'new@user.com',
organisationId: 'existing-organisation-id'
}).then(() => {
models.User.findOne({
where: {
email: 'new@user.com',
},
include: [
{ model: models.Organisation, attributes: ['name'] },
],
});
});
我已经彻底阅读了这些文档,但我想我一定漏掉了一些东西。我要连接的数据库是 PostgreSQL。非常感谢有人指出我正确的方向。
【问题讨论】:
-
你在使用 Postgresql 吗?
-
是的,这可能值得注意!
-
@nomadoda 你找到解决办法了吗?
-
我也遇到了同样的问题,哈哈。
标签: sql node.js postgresql sequelize.js