如何查询多对多关系sequelize?

2022-01-19 00:00:00 node.js javascript mysql sequelize.js

表有多对多的关系,由一个订单表连接.

Tables have many to many relationship, junction by an order table in between.

Outlet --> 订购 <-- 产品

Outlet --> Order <-- Product

我想获取今天订单的奥特莱斯列表.

I want to get the list of Outlet for today Order.

所以这里有一个获取所有网点的函数:

So here is a function to get all outlets:

db.Outlet.findAll({include: [
    {model:db.Product, attributes: ['id', 'name', 'nameKh']}
    ]}).then(function(outlets){
    return res.jsonp(outlets);
})

我得到了这个结果:

我只能选择 where Product Id by using this:

I can only select with where Product Id by using this:

db.Outlet.findAll({include: [
    {model:db.Product, attributes: ['id', 'name', 'nameKh'], where: {id: 2}
    ]}).then(function(outlets){
    return res.jsonp(outlets);
})

如何查询具体的订单金额,或者今天的订单日期?

How can I query by specific order amount, or today order date?

这是我的模型:

出口:

var Outlet = sequelize.define('Outlet', {
            outletCode: DataTypes.STRING,
            outletName: DataTypes.STRING,
            outletNameKh: DataTypes.STRING,
            outletSubtype: DataTypes.STRING,
            perfectStoreType: DataTypes.STRING,
            address: DataTypes.STRING
        },
        {
            associate: function(models){
                Outlet.belongsToMany(models.Product, {through: models.Order});
                Outlet.belongsTo(models.Distributor);
                // Outlet.hasMany(models.Order);
            }
        }
    );

产品:

var Product = sequelize.define('Product', {
            inventoryCode: DataTypes.STRING,
            name: DataTypes.STRING,
            nameKh: DataTypes.STRING,
            monthlyCaseTarget: DataTypes.INTEGER,
            pieces: DataTypes.INTEGER,
            star: DataTypes.BOOLEAN,
            price: DataTypes.FLOAT,
            active: DataTypes.BOOLEAN
        },
        {
            associate: function(models){
                Product.belongsToMany(models.Outlet, {through: models.Order});
                Product.belongsTo(models.Category);
                // Product.hasMany(models.Order);
            }
        }
    );

订单:

var Order = sequelize.define('Order', {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            amount: DataTypes.INTEGER
        },
        {
            associate: function(models){
                Order.belongsTo(models.Outlet);
                Order.belongsTo(models.Product);
                Order.belongsTo(models.User);
            }
        }
    );

推荐答案

试试看:

db.Outlet.findAll({
    include: [{
        model:db.Product, 
        attributes: ['id', 'name', 'nameKh'], 
        through: { where: { amount: 10 } }
    }]
})

相关文章