如何在Sequelize JS中限制一个includesToMany关联包括?

问题描述 投票:1回答:1

我目前在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'
            ]
        ]
    })

这是当前的获取,但是如果我对include添加一个限制,它告诉我只有hasMany可以拥有{separate: true}

总而言之,我要实现的是返回n个ProductList,每个ProductList仅附有m个Product。

mysql node.js sequelize.js
1个回答
0
投票
设法使它像这样工作,看起来并不理想,但确实可以完成工作:

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' ] ] })

© www.soinside.com 2019 - 2024. All rights reserved.