postgresql - 'select' 附近的 Knex.js SQL 语法错误

标签 postgresql coffeescript knex.js

我遇到了一个奇怪的错误:

{ __cid: '__cid9',
  method: 'insert',
  options: undefined,
  bindings: 
   [ 500,
     'Dinner',
     '10/02/2015 7:57 PM',
     '09/29/2015 8:00 PM',
     'Grand Plaza',
     1 ],
  sql: 'insert into "expense" ("amount", "description", "due_date", "payment_date", "vendor_id") values ($1, $2, $3, $4, select "vendor_id" from "vendor" where "name" = $5 limit $6)',
  returning: undefined }
error: syntax error at or near "select"
at [object Object].Connection.parseE (/.../node_modules/pg/lib/connection.js:534:11)
  at [object Object].Connection.parseMessage (/.../node_modules/pg/lib/connection.js:361:17)
  at Socket.<anonymous> (/.../node_modules/pg/lib/connection.js:105:22)
  at Socket.emit (events.js:107:17)
  at readableAddChunk (_stream_readable.js:163:16)
  at Socket.Readable.push (_stream_readable.js:126:10)
  at TCP.onread (net.js:538:20)

我已经使用那些剪切和粘贴的值运行了原始 SQL,它工作得很好。

这是产生错误的代码:

Promise.each subbudget.expenses, (expense) ->
    vendor.get(expense.vendor).then (vendor_id) ->
        knex('expense').insert(
            due_date: expense.dueDate
            vendor_id: (knex.first("vendor_id").from("vendor").where({name: vendor_id}))
            amount: expense.amount
            description: expense.description
            payment_date: expense.paidDate
        )

编辑(部分解决方案): 问题似乎是 SELECT 语句周围缺少括号。 Knex 提供仅适用于原始语句的 .wrap() 和仅适用于嵌套语句的 .as();出于某种原因,这不符合嵌套语句的条件,所以我不能在它周围加上括号。有什么想法吗?

最佳答案

knex.raw("("+ knex.first("vendor_id").from("vendor").where({name: vendor_id}).toString() + ")")

不是最干净的,但使用.toString(),然后将其包装在.raw()

关于postgresql - 'select' 附近的 Knex.js SQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32915891/

相关文章:

node.js - Coffeescript --watch 开关不适用于 Node 0.4.7

postgresql 不按我的时间戳聚合

mysql - 在 ubuntu 中将 postgres 转储转换为 mysql 转储

postgresql - 在 array() 中进行更新

jquery - Coffeescript 从回调方法中获取适当的范围

mysql - 更改 Knex rawquery 的输出

postgresql - psql : FATAL: role "vagrant" does not exist

ruby-on-rails - Backbone.js + Handlebars 每个

javascript - 使用 aws Secret Manager 配置 knexfile.js

javascript - 尝试让 package.json knex 命令起作用