Reputation: 127
I'm new to Sequelize and I'm having a hard time to understand this. This is my raw query:
select * from routes r join transports t where origin like :origin and destination like :destination and convert(departure, date) like convert(:date, date) and r.transportId = t.id
I want to do this in Sequelize, and looking at the docs I have tried this:
const { Sequelize, Op } = require("sequelize");
Route.findAll({
where: {
destination,
origin,
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'): {
[Op.like]: Sequelize.fn('CONVERT', date, 'date'))
}
},
include: [{
model: db.transport,
as: 'transport'
}]);
But I get syntax errors.
Edit:
Route.findAll({
where: {
destination,
origin,
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'), {
[Op.like]: Sequelize.fn('CONVERT', date, 'date')
})
},
include: [{
model: db.transport,
as: 'transport'
}]
});
I still get same syntax error:
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'), {
^
SyntaxError: Unexpected token '.'
Edit:
Route.findAll({
where: {
[Op.and]: [
{ destination, origin },
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'), {
[Op.like]: Sequelize.fn('CONVERT', date, 'date')
})
]
},
include: [{
model: db.transport,
as: 'transport'
}]
});
It removed the previous syntax error. Now I get this one:
SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''date') LIKE CONVERT('2020-05-28 00:00:00', 'date'))' at line 1
Upvotes: 1
Views: 2855
Reputation: 127
I have figured it out. I finally had to use Sequelize.literal to make it work:
Route.findAll({
where: {
[Op.and]: [
{ destination },
{ origin },
Sequelize.where(Sequelize.literal('CONVERT(departure, date)'), {
[Op.like]: Sequelize.literal('CONVERT("' + date + '", date)')
})
]
},
include: [{
model: db.transport,
as: 'transport'
}]
});
Upvotes: 1
Reputation: 3032
just format it properly
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'),
{
[Op.like]: Sequelize.fn('CONVERT', 'date', date)
}
)
where: {
[Op.and]: [
{ destination: {[Op.like]: destination }},
{ origin: {[Op.like]: origin }},
Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'),
{
[Op.like]: Sequelize.fn('CONVERT', date, 'date')
})
]
}
Upvotes: 2