La façon simple de faire une requête de sélection dans knex est la suivante:
db('table_name').where({ id: 1 }).select();
Mais, il renvoie un tableau. Puisque id
est un champ unique, il est clair que je
attendez-vous à un seul résultat. Et puis, je dois faire quelque chose comme ça:
db('table_name').where({ id: 1 }).select().then(result => result[0]);
Existe-t-il un moyen _officiel_ de renvoyer une valeur unique?
db('table_name').where({id: 1}).first().then((row) => row)
Devrait marcher
Oh, c'est en fait first
et je continue à chercher one
, selectOne
, etc. Merci
db ('nom_table'). where ({id: 1}). first (); cela fonctionnerait de la même manière. non?
@ arch-mage S'il ne doit y avoir qu'un seul résultat correspondant, alors c'est une meilleure pratique pour le garantir, les implémentations courantes single
font en utilisant limit 2
. Voici comment l'ajouter à 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 seriez-vous intéressé par un PR ajoutant la méthode single
à QueryInterface
?
Commentaire le plus utile
db('table_name').where({id: 1}).first().then((row) => row)
Devrait marcher