Knex: ¿Cuál es la forma correcta de devolver un solo valor de la consulta de selección?

Creado en 18 abr. 2016  ·  4Comentarios  ·  Fuente: knex/knex

La forma sencilla de hacer una consulta de selección en knex es así:

db('table_name').where({ id: 1 }).select();

Pero devuelve una matriz. Dado que id es un campo único, está claro que yo
esperar un único resultado. Y luego, tengo que hacer algo como esto:

db('table_name').where({ id: 1 }).select().then(result => result[0]);

¿Existe alguna forma _oficial_ de devolver un solo valor?

question

Comentario más útil

db('table_name').where({id: 1}).first().then((row) => row)

Deberia trabajar

Todos 4 comentarios

db('table_name').where({id: 1}).first().then((row) => row)

Deberia trabajar

Oh, en realidad es first y sigo buscando one , selectOne , etc. Gracias

db ('nombre_tabla'). donde ({id: 1}). first (); esto funcionaría igual. ¿No?

@ arch-mage Si debe haber un solo resultado coincidente, entonces es una mejor práctica para asegurarlo, las implementaciones comunes de single hacen usando limit 2 . A continuación, le indicamos cómo agregarlo a Knex.

import Knex from 'knex'

declare module 'knex' {
  interface QueryInterface {
    _method: string
    _isSelectQuery: () => boolean
    single: (columns?: string | string[], notFoundMessage?: string, notSingleMessage?: string) => Promise<any>
  }
}

Knex.QueryBuilder.extend('single', function single(
  this: Knex.QueryBuilder,
  columns: string | string[] = '*',
  notFoundMessage?: string,
  notSingleMessage?: string,
): any {
  // eslint-disable-next-line no-underscore-dangle
  if (!this._isSelectQuery() || this._method === 'first')
    // eslint-disable-next-line no-underscore-dangle
    throw new Error(`Cannot chain .single() on "${this._method}" query!`)
  // eslint-disable-next-line no-param-reassign
  if (typeof columns === 'string') columns = [columns]
  const allColumns = columns.includes('*')
  const singleColumn = !allColumns && columns.length === 1 ? columns[0] : false
  if (!allColumns) this.select(...columns)
  this.limit(2)
  return this.then((results: any[]) =>
    results.length === 1
      ? singleColumn
        ? results[0][singleColumn]
        : results[0]
      : results.length
      ? Promise.reject(notSingleMessage || `Query has more than one result: "${this.toSQL().sql}"`)
      : Promise.reject(notFoundMessage || `Query has no results: "${this.toSQL().sql}"`),
  )
} as any)

@wubzz , ¿le interesaría que un RP agregue el método single a QueryInterface ?

¿Fue útil esta página
0 / 5 - 0 calificaciones