Reputation: 320
I have written a SQL query and am trying to adapt it to Sequelize but cannot figure out how to create an association on the same table. Here is the SQL:
SELECT t1.*
FROM `configurations` t1
INNER JOIN
(
SELECT max(configuration_start) maxConfigStart, pb_id
FROM `configurations`
WHERE
active = 1
AND DATE(configuration_start) <= DATE(NOW())
GROUP BY `pb_id`
) t2
ON t1.`pb_id` = t2.`pb_id`
AND t1.`configuration_start` = t2.`maxConfigStart`
WHERE t1.`active` = 1
ORDER BY t1.`configuration_start` DESC
Here is the model definition:
configurations = sequelize.define 'configurations', {
id:
type: Sequelize.INTEGER
primaryKey: true
autoIncrement: true
configuration_name: Sequelize.STRING
configuration_start: Sequelize.DATE
configuration_end: Sequelize.DATE
created: Sequelize.DATE
updated: Sequelize.DATE
}, {
timestamps: false,
scopes: {
currentConfigTimes: {
attributes: ['pb_id', [sequelize.fn('max', sequelize.col('configuration_start')), 'configuration_start']]
where:
active: 1
configuration_start:
lte: new Date()
group: ['pb_id']
},
currentConfigIds: {
attributes: ['pb_id', 'configuration_start', 'id']
where:
active: 1
configuration_start:
lte: new Date()
order: [['configuration_start', 'DESC']]
}
}
}
Any help that someone can offer would be very much appreciated. Essentially I am trying to get the most recent past configuration for every pb_id
. Maybe there is a better way of doing it?
Upvotes: 0
Views: 1645
Reputation: 320
It appears that this is actually not possible using Sequelize currently. After spending a great deal of time with their documentation trying to understand the best way of doing this, I came upon this Github issue trying to solve the exact same problem. The best solution is to use a raw query at this time.
Upvotes: 1