Knex: Qual é a maneira correta de retornar um único valor da consulta selecionada?

Criado em 18 abr. 2016  ·  4Comentários  ·  Fonte: knex/knex

A maneira simples de selecionar consulta no knex é assim:

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

Mas, ele retorna uma matriz. Como id é um campo único, é claro que eu
espere um único resultado. E então, eu tenho que fazer algo assim:

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

Existe alguma maneira _oficial_ de retornar um único valor?

question

Comentários muito úteis

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

Deveria trabalhar

Todos 4 comentários

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

Deveria trabalhar

Oh, na verdade é first e continuo procurando por one , selectOne , etc. Obrigado

db ('nome_tabela'). where ({id: 1}). first (); isso funcionaria da mesma forma. não?

@ arch-mage Se deveria haver apenas um único resultado correspondente, então é uma prática recomendada garantir isso, single implementações comuns fazem isso usando limit 2 . Veja como adicioná-lo ao 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 , você estaria interessado em um PR adicionando o método single a QueryInterface ?

Esta página foi útil?
0 / 5 - 0 avaliações

Questões relacionadas

marianomerlo picture marianomerlo  ·  3Comentários

aj0strow picture aj0strow  ·  3Comentários

legomind picture legomind  ·  3Comentários

hyperh picture hyperh  ·  3Comentários

fsebbah picture fsebbah  ·  3Comentários