我在SQL数据库中有两个表,它们具有一对多的关系。我正在使用sequelize.js对此进行建模。每个表都有一个日期字段。我想编写一个findAll查询,它可以执行LEFT JOIN并过滤具有特定范围内日期的任何行。我可以用SQL编写查询,但我不知道如何编写一个选项对象传递给findAll以重现相同的查询。
下面是设置:
class Customer extends Model {}
Customer.init( {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
date_of_registration: DataTypes.DATE
} );
class Purchase extends Model {}
Purchase.init( {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
date_of_purchase: DataTypes.DATE
} );
Customer.hasMany( Purchase, {
foreignKey: { allowNull: false, name: 'customer_id' }
} );
Purchase.belongsTo( Customer, {
foreignKey: { allowNull: false, name: 'customer_id' }
} );
字符串
下面是我想运行的查询:
SELECT Customer.date_of_registration,
Purchase.date_of_purchase
FROM Customer
LEFT JOIN Purchase
ON Customer.id = Purchase.customer_id
WHERE Customer.date_of_registration > '2023-10-24'
OR Purchase.date_of_purchase > '2023-10-24'
GROUP BY Customer.id;
型
我尝试过很多不正确的方法,但最接近的方法是将date_of_purchase的查询放在LEFT JOIN的ON子句中,而不是放在WHERE子句下的OR子句中。
Customer.findAll( {
where: {
date_of_registration: {
[ Op.gt ]: new Date( '2023-10-24' )
}
},
include: [ {
model: Purchase,
where: {
date_of_purchase: {
[ Op.gt ]: new Date( '2023-10-24' )
}
},
attributes: [],
required: false
} ]
} );
型
此查询输出以下SQL:
SELECT "Customer"."id", "Customer"."date_of_registration", "Purchase"."date_of_purchase"
FROM "customer" AS "Customer"
LEFT OUTER JOIN "purchase" AS "Purchase"
ON "Customer"."id" = "Purchase"."customer_id"
AND "Purchase"."date_of_purchase" > '2023-10-24 00:00:00.000 +00:00'
WHERE "Customer"."date_of_registration" > '2023-10-24 00:00:00.000 +00:00'
GROUP BY "Customer"."id";
型
如何修改Customer.findAll调用以输出第一个查询而不使用Raw Query?
1条答案
按热度按时间e5njpo681#
我不确定是否通过模型的
findAll
将整个原始SQL查询表示为Sequelize查询(因为它是一个聚合查询,并且几乎总是很难编写这样的查询w/o literals或作为Sequelize中的普通SQL查询),但对于表示给定的OR条件,它可能看起来像这样:字符串