最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to select the first element of a column of type array column using knex.select()? - Stack Overflow

programmeradmin4浏览0评论

We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

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

Expecting the first element of images column of items table.

We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

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

Expecting the first element of images column of items table.

Share Improve this question asked May 26, 2019 at 8:40 Pratap SharmaPratap Sharma 2,7632 gold badges22 silver badges36 bronze badges 3
  • Is icon column is of a type json? – felixmosh Commented May 26, 2019 at 10:43
  • An icon is not the column Images is a column of type text[] @felixmosh – Pratap Sharma Commented May 26, 2019 at 15:15
  • How it will look like in regular SQL string, without Knex? – felixmosh Commented May 26, 2019 at 20:03
Add a ment  | 

2 Answers 2

Reset to default 3

Try using the first() function. It returns the first row in your table (in whatever order the table is sorted). The .select('images') will limit the columns returned to just 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]);
})

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

This seems to build correct kind of query for it in knex (notice that in postgresql arrays starts from index 1):

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

Here is runkit example of generated query https://runkit./embed/1apx76bh4u40

发布评论

评论列表(0)

  1. 暂无评论