将原始查询转换为sequelize

vsdwdz23  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(362)

我是新来续集的,我很难理解这一点。这是我的原始查询:

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

我想在sequelize中这样做,看看我尝试过的文档:

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

但我有语法错误。
编辑:

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

我仍然得到相同的语法错误:

Sequelize.where(Sequelize.fn('CONVERT', Sequelize.col('departure'), 'date'), {
          ^

SyntaxError: Unexpected token '.'

编辑:

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

它删除了以前的语法错误。现在我得到这个:

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
nqwrtyyt

nqwrtyyt1#

把它格式化就行了

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

ddhy6vgd2#

我已经弄明白了。我最后不得不使用sequelize.literal来实现它:

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

相关问题