【问题标题】:How to concat columns in Sequelize with SQLite database如何使用 SQLite 数据库连接 Sequelize 中的列
【发布时间】:2021-05-12 04:00:39
【问题描述】:

我正在将 Sequelize 用于我正在进行的快速项目。
在一个查询中,我想检索两列的串联结果。

喜欢:

SELECT first_name || ' ' || last_name AS full_name FROM table

我尝试了以下语法并得到了错误

router.get('/persons', function(req, res, next) {
  models.Person.findAll({
    attributes: [models.sequelize.fn('CONCAT', 'first_name', 'last_name')]
  })
    .then(function(persons) {
      res.send(persons);
    });
});

错误信息:

SELECT CONCAT('first_name', 'last_name') FROM `Persons` AS `Person`;
Possibly unhandled SequelizeDatabaseError: Error: SQLITE_ERROR: no such function: CONCAT

【问题讨论】:

  • 您是否尝试过使用literal?我没有在任何地方设置 Sequelize,所以我无法检查,但也许像 models.sequelize.literal("first_name || ' ' || last_name") 这样的东西会起作用。
  • 谢谢!它现在正在工作(:

标签: sqlite express sequelize.js


【解决方案1】:

我使用了models.sequelize.literal,它创建了一个表示文字的对象, 在嵌套数组中给它一个别名。

结果:

router.get('/persons', function(req, res, next) {
  models.Person.findAll({
    attributes: [models.sequelize.literal("first_name || ' ' || last_name"), 'full_name']
  })
    .then(function(persons) {
      res.send(persons);
    });
});

【讨论】:

  • 如何将字符串与属性的列值连接起来?
【解决方案2】:

重构为 ES6 并异步等待

const {fn, col } = models.sequelize
const { Person } = models

router.get('/persons', async(req, res, next) => {
  try { 
      const persons = await Person.findAll({
        attributes: [fn('CONCAT', col('first_name'), ' ', col('last_name'))]
      })
      res.send(persons);
  } catch (err) {
      next(err)
  }
});

【讨论】:

  • fn('CONCAT' 不适用于 SQLite 数据库,我们需要 || 运算符。
【解决方案3】:

我有同样的问题,我是这样解决的

const { fn, col } = Person.sequelize;

const res = Person.findAll({
   attributes: [ [fn('concat', col('first_name'), ' ', col('last_name')), "FullName"], ...OthersColumns ]
})

希望对你或其他人有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多