knex์์ ์ ํ ์ฟผ๋ฆฌ๋ฅผ ์ํํ๋ ๊ฐ๋จํ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
db('table_name').where({ id: 1 }).select();
๊ทธ๋ฌ๋ ๋ฐฐ์ด์ ๋ฐํํฉ๋๋ค. id
์ ๊ณ ์ ํ ํ๋์ด๋ฏ๋ก
๋จ์ผ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ํฉ๋๋ค. ๊ทธ๋ฐ ๋ค์ ๋ค์๊ณผ ๊ฐ์ดํด์ผํฉ๋๋ค.
db('table_name').where({ id: 1 }).select().then(result => result[0]);
๋จ์ผ ๊ฐ์ ๋ฐํํ๋ _official_ ๋ฐฉ๋ฒ์ด ์์ต๋๊น?
db('table_name').where({id: 1}).first().then((row) => row)
์๋ํด์ผ
์, ์ค์ ๋ก first
์ด๊ณ ๊ณ์ํด์ one
, selectOne
๋ฑ์ ์ฐพ์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค.
db ( 'table_name'). where ({id : 1}). first (); ์ด๊ฒ์ ๋์ผํ๊ฒ ์๋ํฉ๋๋ค. ์๋?
@ arch-mage ์ผ์นํ๋ ๊ฒฐ๊ณผ๊ฐ ํ๋๋ง ์์ด์ผํ๋ ๊ฒฝ์ฐ์ด๋ฅผ ๋ณด์ฅํ๋ ๊ฒ์ด ๊ฐ์ฅ ์ข์ต๋๋ค. ์ผ๋ฐ์ ์ธ single
๊ตฌํ์์๋ limit 2
์ฌ์ฉํ์ฌ ์ํํฉ๋๋ค. 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 single
๋ฉ์๋๋ฅผ QueryInterface
์ถ๊ฐํ๋ PR์ ๊ด์ฌ์ด ์์ต๋๊น?
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
db('table_name').where({id: 1}).first().then((row) => row)
์๋ํด์ผ