【问题标题】:How to limit includes on a belongsToMany association in Sequelize JS?如何限制包含在 Sequelize JS 中的 belongsToMany 关联?
【发布时间】:2023-03-24 08:50:01
【问题描述】:

我目前在 Sequelize 中有以下模型:

Product

ProductList.belongsToMany(models.Product, { as: 'products', through: 
sequelize.models.ProductListProduct, foreignKey: 'productListId'});

还有枢轴,ProductListProduct

我目前正在尝试在我的主页上显示一系列productList

并且需要将退回的产品限制为某个值(在这种情况下为 6):

let productLists = await ProductList.findAll({
        where: {
            slug: ['recommended', 'new_and_promos']
        },
        include: [{
            model: Product,
            as: 'products',
            include: ['attributes', 'images'],
            where: {
                active: true
            }
        }],
        order: [
            [
                'products', ProductListProduct, 'position', 'ASC'
            ]
        ]
    })

这是当前获取,但是如果我为包含添加限制,它会告诉我只有 hasMany 可以拥有 {separate: true}

回顾一下,我想要实现的是返回 n 个 ProductList,每个 ProductList 只附加了 m 个产品。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    设法让它像这样工作,看起来并不理想,但确实可以:

    let productLists = await ProductList.findAll({
                where: {
                    slug: ['recommended', 'new_and_promos']
                },
                include: [{
                    model: Product,
                    as: 'products',
                    include: ['attributes', 'images'],
                    where: Sequelize.literal('`products->ProductListProduct`.`position` < 8')
                }],
                order: [
                    [
                        'products', ProductListProduct, 'position', 'ASC'
                    ]
                ]
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多