【问题标题】:Unable to return only nested model properties using sequelize无法使用 sequelize 仅返回嵌套模型属性
【发布时间】:2019-11-10 05:49:00
【问题描述】:

我有模型Product 和模型Category,它们有一个many to many relashionship。我想获得产品所属的所有类别 . 所以这就是我所做的:

const product_categories=await Product.findByPk(product_id,{ include:{ model:Category, as:'categories', },});

查询工作得很好,但在响应中我首先得到了Product object 和嵌套的Category,但我真正想要的是只显示类别。这是结果。

我不想看到Product attributes,我只对嵌套的Category 感兴趣。或者只有product_id valuekey 并在其中嵌套Category。我该如何实现?

【问题讨论】:

    标签: node.js express orm sequelize.js


    【解决方案1】:

    只是翻转逻辑。

    const productCategories = await Category.findAll({
      attributes: ['id', 'name'], // or whatever attributes you want, remove this if you want all of them
      where: {
        productId: product_id
      },
      transaction
    })
    

    另一方面,我认为您可以在仍然使用您的方法的同时删除产品属性:

    const product_categories = await Product.findByPk(product_id,{
      attributes: [], // <== no product attributes
      include:[{
          model:Category,
          as:'categories',
      }],
      transaction
    })
    

    【讨论】:

    • 为什么要添加交易?
    • 交易是必需的。就像银行交易一样,如果一个按钮点击在后面触发了整个调用链,无论是在服务器中还是在服务器和数据库之间,并且无论出于何种原因,其中一个调用失败,必须抛出一个错误,并且在调用失败之前对数据库所做的所有更改都必须恢复。必须进行回滚。如果所有调用都使用相同的事务(您传递它,从路由到端点到另一个端点,到内部函数等等)成功,然后提交数据库更改。检查文档!
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2018-05-10
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多