【问题标题】:display attributes without nesting objects using include in (Sequelize)使用 include in (Sequelize) 显示不嵌套对象的属性
【发布时间】:2021-05-30 13:35:05
【问题描述】:

我有一个模型 SKUValue,它与另外两个模型 VariantOptionsProductVariant 相关联。 我用 VariantOptionsProductVariant 创建了一个 "left-joins" SKUValue 值的 sequelize 查询,并带来了结果.

序列化查询

await SKUValue.findAll({
            where: {
                productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'
            },
            include: [
                {
                    model: VariantOption,
                    attributes: ['name']
                },
                {
                    model: ProductVariant,
                    attributes: ['name']
                }
            ],
            attributes: ['SKUId']
        });

查询结果返回一个数组,其中属性VariantOptionProductVariant是一个嵌套对象,只有一个字段。

[
    {
        "SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
        "VariantOption": {
            "name": "Large"
        },
        "ProductVariant": {
            "name": "Size"
        }
    },
    {
        "SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
        "VariantOption": {
            "name": "Red"
        },
        "ProductVariant": {
            "name": "color"
        }
    }
]

如何查询属性,VariantOptionProductVariant 的结果不返回嵌套对象,而只返回搅拌。

一般来说,我希望结果是这样的

[
    {
        "SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
        "VariantOption.name": "Large",
        "ProductVariant.name": "Size"
    },
    {
        "SKUId": "72edd3ca-fa12-4234-ba8c-dd008eb416d5",
        "VariantOption.name": "Red",
        "ProductVariant.name": "Color"
    }
]

【问题讨论】:

    标签: node.js sequelize.js associations


    【解决方案1】:

    我找到了问题的答案。

    使用Sequelize.literal,我们可以很方便的在外层属性中添加内层属性。

    return await SKUValue.findAll({
                where: {
                    productId: '7bde8a1d-5f6c-4349-bfda-428399c88291'
                },
                include: [
                    {
                        model: VariantOption,
                        attributes: []
                    },
                    {
                        model: ProductVariant,
                        attributes: []
                    }
                ],
                attributes: [
                    'SKUId',
                    [Sequelize.literal('"ProductVariant"."name"'), 'productVariant'],
                    [Sequelize.literal('"VariantOption"."name"'), 'variantOption']
                ]
            });
    

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      相关资源
      最近更新 更多