如何查询多对多关系sequelize? [英] How to query many to many relationship sequelize?

查看:42
本文介绍了如何查询多对多关系sequelize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何查询多对多关系sequelize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆