这是我的代码:
//Models definition
var User = sequelize.define('user', ...);
var Address = sequelize.define('address', ...);
var Club = sequelize.define('club', ...);
//Club scopes
scopes: {
withUser: {
include: [
{ model: User }
]
},
//Models associations
User.hasOne(Address);
Club.hasOne(User);
Club.hasOne(Address);
//Main
//Create address
var addressToCreate = {};
if(body.address) addressToCreate.address = body.address;
if(body.city) addressToCreate.city = body.city;
if(body.zipCode) addressToCreate.zipCode = body.zipCode;
//Get user from db
var user = await User.findByPk(body.user);
var clubToCreate = { name: body.name, phone: body.phone };
//Persist Address in db
return Address.create(addressToCreate)
.then(address => {
//Persist club in db
return Club.create(clubToCreate)
.then(club => {
//Associate User and Address to Club
club.setAddress(address);
club.setUser(user);
//Save club with associated models
return club.save()
})
.then(club => Club.scope('withUser').findByPk(club.id))
.then(club => { console.log(club); return club; })
})
在我的数据库中,表地址包含userId和clubId,表用户包含clubId;
此代码似乎可以用于创建和关联模型。但是console.log显示的最终俱乐部显示用户:null
但是,在db中,表用户中有好行,并且具有引用俱乐部ID的好外键
我的日志显示,选择请求(来自Club.findByPk)在更新之前完成(来自club.save)。就像.then在兑现承诺之前执行
抱歉我的英语不好,希望有人能帮忙
答案 0 :(得分:0)
您正在使用async/await
,但会根据获取用户的代码将其与旧的promise样式混合使用。以下是async/await
样式的代码副本,尽管您可能不需要重新获取club
对象,依此类推,所以继续进行调试。
const address = await Address.create(addressToCreate);
let club = await Club.create(clubToCreate);
console.log('created club', club);
club.setAddress(address);
club.setUser(user);
await club.save();
console.log('saved club', club);
club = await Club.scope('withUser').findByPk(club.id);
console.log('reloaded club', club);
return club;