繁体   English   中英

Sequelize 创建具有关联的实例

[英]Sequelize create instance with association

在 Sequelize 4 中,有两个类: UserProfile ,它们通过

User.associate = (model) => {
    User.hasMany(model.profile);
}

现在我有一个名为user的 User 实例,并且想要创建一个Profile实例,我如何创建它与user关联。

这是我尝试过的。 它有效,但我正在寻找更好的解决方案。

var Profile = require('../models/profile');
Profile.create({userId: user.id})

这是我尝试过但不起作用的另一种方法:

var Profile = require('../models/profile');
Profile.create({user: user},{include: User})

有什么想法吗?

嗯,这有帮助:

var profile = new Profile();
profile.setUser(user);
Profile.create(profile).then(res.send('success'));

创建(或构建并保存)您的配置文件和用户实例。 在配置文件上设置用户。 保存配置文件(再次)。

像这样的东西:

const profile = Profile.build({...});
profile.save();

const user = User.build({...});
user.save();

profile.setUser(user);

profile.save();

在实践中,在构建 newUser 和配置文件后,promise 可能看起来更像这样:

newUser.save().catch(err => console.log('Failed to create user', err))

profile.save()
.then(profile => profile.setUser(user))
.then(profile => profile.save())
.then(profile => {
  res.json(profile)
})
.catch(err => console.log('Failed to create profile', err));

试试这个,

User.associate = (model) => {
    User.hasMany(model.profile, as "profile");
}

那么

User.create({user: user, profile:profile},{include: Profile, as : "profile"})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM