续集:特殊方法不更新数据库? - 问题更新实例
我花了一天的时间对我的一种方法的行为感到困惑,该方法应该创建一个模型的实例,company
,它具有contact> contact
。
我觉得它应该很简单,但是它只是不会像我期望的那样输出联系人
字段,即使它正确地将其保存到数据库中:
await sequelize.transaction(async (t) => {
const company = await Company.create({ name: req.body.companyName }, { transaction: t });
const contact = await Contact.create({position: req.body.position}, { transaction: t });
await company.addContact(contact, {transaction: t}); // This method does exist
await company.save(); // Thought this might help in case `addContact` didn't update the db
console.log(company.dataValues); // {id:5, name: 'test'}
console.log(contact.dataValues); // {id: 7, position: 'Legend'}
const test = await Company.findOne({where: { name: req.body.companyName }, transaction: t});
console.log(test.dataValues); // {id: 5, name: 'test'}, no contact property
console.log(company.contacts); // is this not posssible instead?
//...
我期望这是输出:
{{ id:5, 名称:“测试”, 联系人:[{id:7,位置:'legend'}] }
真的不明白为什么它不起作用。在这一点上,任何帮助都将不胜感激!
**协会:
Company.hasMany(Contact);
Contact.belongsTo(Company);
I've spent a decent chunk of the day confused about the behaviour of one of my methods that should create an instance of a Model, Company
, that has a Contact
.
I feel like it should be simple, but it's just not outputting the contact
field as I'd expect, even though it is saving it to the database correctly:
await sequelize.transaction(async (t) => {
const company = await Company.create({ name: req.body.companyName }, { transaction: t });
const contact = await Contact.create({position: req.body.position}, { transaction: t });
await company.addContact(contact, {transaction: t}); // This method does exist
await company.save(); // Thought this might help in case `addContact` didn't update the db
console.log(company.dataValues); // {id:5, name: 'test'}
console.log(contact.dataValues); // {id: 7, position: 'Legend'}
const test = await Company.findOne({where: { name: req.body.companyName }, transaction: t});
console.log(test.dataValues); // {id: 5, name: 'test'}, no contact property
console.log(company.contacts); // is this not posssible instead?
//...
I was expecting this as the output:
{
id: 5,
name: 'test',
contacts: [{ id: 7, position: 'legend' }]
}
Really can't understand why it's not working. Any help would be really appreciated at this point!
** Associations:
Company.hasMany(Contact);
Contact.belongsTo(Company);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论