【问题标题】:How to select the first element of a column of type array column using knex.select()?如何使用 knex.select() 选择数组列类型的列的第一个元素?
【发布时间】:2019-05-27 16:50:03
【问题描述】:

我们可以在 Postgres SQL 数据库中选择数组类型列的第一个元素。但我无法使用 knex 查询相同的内容。

我试过了。

database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data) 
}

期待 items 表的 images 列的第一个元素。

【问题讨论】:

  • icon 列是否属于 json 类型?
  • 图标不是列图像是文本类型的列[] @felixmosh
  • 在没有 Knex 的情况下,它在常规 SQL 字符串中的外观如何?

标签: javascript arrays knex.js


【解决方案1】:

尝试使用first() 函数。它返回表中的第一行(以表的排序顺序)。 .select('images') 会将返回的列限制为仅images

knex
  .select('images')
  .table('items')
  .first()
  .then((data) => {
    // first row of 'images' is an array.
    // return only the first item in array.
    res.send(data[0]);
})

【讨论】:

  • 上面的承诺返回图像列的行。我想要图像列第一行的第一项。 @user45392
  • @PratapSharma 在这种情况下,请尝试res.send(data[0]);。请参阅上面的编辑。
  • 如果没有满足查询的行怎么办?
  • @Noname 它应该仍然有效,只是返回一个空结果。在这种情况下,由于预期结果是一个数组,索引data[0] 可能会出错
【解决方案2】:

https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING

这似乎在 knex 中为它构建了正确的查询类型(注意在 postgresql 数组中从索引 1 开始):

knex('items').select({icon: knex.raw('??[1]', ['images'])})

这是生成查询https://runkit.com/embed/1apx76bh4u40的runkit示例

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2013-12-24
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多