我正在尝试构建用户,创建位置(我正在使用Google地理编码API)并保存所有内容,但不会在数据库中创建关联。一切都很好。响应正是我想要的,但是当我进入数据库时,不会创建关联。我使其工作的唯一方法是单独创建和保存位置实体,并直接将外键“locationId”设置为新生成的ID。已经差不多一个星期,我仍然无法弄清楚如何让它发挥作用。如果它可以帮助,我也使用PostgreSQL。以下是creation with associations.
的文档以下是我的协会:
User.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });
Location.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });
这是我的控制器代码:
const createRandomToken = crypto
.randomBytesAsync(16)
.then(buf => buf.toString('hex'));
const createUser = token => User.build({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
passwordResetToken: token,
passwordResetExpires: moment().add(1, 'days'),
role: req.body.roleId,
active: true
}, {
include: [{ model: Location, as: 'location' }]
});
const createLocation = (user) => {
if (!user) return;
if (!req.body.placeId) return user;
return googleMapsHelper.getLocationByPlaceId(req.body.placeId).then((location) => {
user.location = location;
return user;
});
};
const saveUser = (user) => {
if (!user) return;
return user.save()
.then(user => res.json(user.getPublicInfo()));
};
createRandomToken
.then(createUser)
.then(createLocation)
.then(saveUser)
.catch(Sequelize.ValidationError, (err) => {
for (let i = 0; i < err.errors.length; i++) {
if (err.errors[i].type === 'unique violation') {
return next(createError.Conflict(err.errors[i]));
}
}
})
.catch(err => next(createError.InternalServerError(err)));
以下是回复:
{
"id": 18,
"firstName": "FirstName",
"lastName": "LastName",
"email": "test@test.com",
"lastLogin": null,
"passwordResetExpires": "2018-04-15T21:02:34.624Z",
"location": {
"id": 5,
"placeId": "ChIJs0-pQ_FzhlQRi_OBm-qWkbs",
"streetNumber": null,
"route": null,
"city": "Vancouver",
"postalCode": null,
"country": "Canada",
"region": "British Columbia",
"formatted": "Vancouver, BC, Canada",
"createdAt": "2018-04-14T20:57:54.196Z",
"updatedAt": "2018-04-14T20:57:54.196Z"
}
答案 0 :(得分:0)
在使用sequelize Github来回一对之后,我实现了使用事务,设置器和修改我的承诺逻辑来做同样的事情。
const createLocation = new Promise((resolve, reject) => {
if (!req.body.placeId) return resolve();
googleMapsHelper
.getLocationByPlaceId(req.body.placeId)
.then(location => resolve(location))
.catch(() => reject(createError.BadRequest('PlaceId invalide')));
});
const createUser = () => sequelize.transaction((t) => {
const user = User.build({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
passwordResetToken: crypto.randomBytes(16).toString('hex'),
passwordResetExpires: moment().add(1, 'days'),
active: true
});
return user.save({ transaction: t })
.then(user => createLocation
.then(location => user.setLocation(location, { transaction: t })));
});
createUser
.then(user => res.json(user))
.catch(err => httpErrorHandler(err, next));