【问题标题】:Use alias in sequelize query wheres attribute?在 sequelize 查询 wheres 属性中使用别名?
【发布时间】:2019-12-11 16:46:22
【问题描述】:

这是我的示例代码,我的问题是如何在查询中将“cityName”设为别名

const test = await test.findAll({
    where: { cityName: { $like: '%' + searchWord + '%' } },
    attributes: ['a', 'b']
})

对不起我的英语水平 这是我的补充说明,我想用参数来代替'cityName'

let NewCityName = 'something'

const test = await test.findAll({
    where: { NewCityName: { $like: '%' + searchWord + '%' } },
    attributes: ['a', 'b']
})

这段代码不起作用,但它似乎有助于理解问题。

【问题讨论】:

    标签: sql node.js sequelize.js


    【解决方案1】:

    是的,这是可能的。试试这个。

    const test = await test.findAll({
    where: { cityName: { $like: '%' + searchWord + '%' } },
    attributes: ['id',['cityName', 'city']]
    })
    

    此处cityName 将别名为city

    【讨论】:

    • 不推荐使用$like,请改用[Op.like]: %${searchword}%
    • 仅当您使用 >=v5
    【解决方案2】:

    我解决了。 我从 Sequelize API Reference 的“Operator Alias”部分得到了一个想法

    const test = {
      where: { cityName: { $like: '%' + searchWord + '%' } }
    }
    
    const test = await test.findAll({
      test,
      attributes: ['a', 'b']
    })
    

    通过给整个 'where' 起别名来解决

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多