无法使用sequelize仅返回嵌套模型属性

时间:2019-06-28 09:08:15

标签: node.js express orm sequelize.js

我有一个Product型号的Category和一个many to many型号。我想获得所有类别,其中一个产品属于。 所以这是我所做的:

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

查询工作正常,但在响应中我首先得到带有嵌套Product object的{​​{1}},但我真正想要的只是显示类别。这里是结果。 e

我不想看到Category,我只对嵌套的Product attributes感兴趣。或者只有Categoryproduct_id value并将{{ 1}}。如何实现此目标?

1 个答案:

答案 0 :(得分: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
})
相关问题