续集:特殊方法不更新数据库? - 问题更新实例

发布于 2025-02-06 15:22:35 字数 1212 浏览 0 评论 0原文

我花了一天的时间对我的一种方法的行为感到困惑,该方法应该创建一个模型的实例,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文