How to query many to many relationship sequelize?(如何查询多对多关系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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何查询多对多关系sequelize?
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
