On this page
クエリビルダー
はじめに
dframeworkはデータベースクエリを構築するための流暢でチェーン可能なクエリビルダーを提供します。プリペアドステートメントのみに依存することでSQLインジェクション攻撃から保護します。バインディングを手動でクリーンアップまたはサニタイズする必要はありません。
グローバルに利用可能なDBファサードのtableメソッドを呼び出してクエリビルダーチェーンを開始します。
1const builder = DB.table('users');2// builder: TableQuery. chainable, thenable, and async iterable.
メソッド一覧
クエリビルダーは制約メソッド(ビルダーを返す)をチェーンして構築されターミナルメソッド(Promiseを返す)で終了します。以下の戻り値列には実際の解決値を示します。
チェーン可能な制約メソッド
これらのメソッドはそれぞれチェーン用に同じTableQueryインスタンスを返します。
| メソッド | 引数 |
|---|---|
from(table) |
対象テーブル名またはエイリアス(ビルダーのソーステーブルを更新) |
select(columns) |
カラム名(現在のselectリストを置き換え) |
selectRaw(expression, bindings?) |
生のSQLフラグメントと任意のバインディング |
selectSub(query, as) |
エイリアス付きスカラサブクエリ式 |
distinct(columns?) |
distinctを指定(オプションでselectリストを置き換え) |
where(column, operator?, value?) |
カラム名/値、{ column: value }オブジェクト、またはクロージャ |
whereNot(条件) |
whereの否定形(クロージャをサポート) |
orWhere(条件) |
whereのor形(クロージャをサポート) |
orWhereNot(条件) |
whereNotのor形(クロージャをサポート) |
whereIn(column, values) |
カラム名と値の配列、またはサブクエリクロージャ |
whereNotIn(column, values) |
whereInの否定形(サブクエリクロージャをサポート) |
orWhereIn(条件) / orWhereNotIn(条件) |
IN句のor形式 |
whereExists(callback) / whereNotExists(callback) |
exists / not existsサブクエリチェック |
orWhereExists(callback) / orWhereNotExists(callback) |
existsチェックのor形式 |
whereNull(column) / whereNotNull(column) |
nullチェック |
orWhereNull(column) / orWhereNotNull(column) |
nullチェックのor形式 |
whereBetween(column, [min, max]) / whereNotBetween(条件) |
範囲チェック(厳密に2つの値が必要) |
orWhereBetween(条件) / orWhereNotBetween(条件) |
範囲チェックのor形式 |
whereColumn(column, operator?, otherColumn) |
同じ行内の2つのカラムを比較 |
orWhereColumn(column, operator?, otherColumn) |
カラム比較のor形式 |
whereRaw(sql, bindings?) |
生のSQL where条件(任意のバインディング付き) |
orWhereRaw(sql, bindings?) |
生のSQL or where条件(任意のバインディング付き) |
whereHashed(column, operator?, value) / orWhereHashed(条件) |
値の高速ハッシュ値との比較 |
when(value, callback, defaultCallback?) |
値がtruthyの場合にコールバックを適用 |
unless(value, callback, defaultCallback?) |
値がfalsyの場合にコールバックを適用 |
join(table, first, operator?, second) |
別のテーブルとの内部結合(joinクロージャをサポート) |
leftJoin(table, first, operator?, second) |
別のテーブルとの左外部結合(joinクロージャをサポート) |
rightJoin(table, first, operator?, second) |
別のテーブルとの右外部結合(joinクロージャをサポート) |
crossJoin(table) |
別のテーブルとのクロス結合 |
joinRaw(expression, bindings?) |
パラメータバインディング付きの生のjoin句 |
groupBy(columns) |
グループ化カラム |
having(column, operator?, value?) |
グループ化結果に対するhaving条件 |
orHaving(column, operator?, value?) |
グループ化結果に対するhaving条件のor形式 |
havingRaw(sql, bindings?) |
生のSQL having条件(任意のバインディング付き) |
orHavingRaw(sql, bindings?) |
生のSQL or having条件(任意のバインディング付き) |
orderBy(column, direction='ASC') |
ソート(方向は'ASC'または'DESC') |
orderByRaw(sql) |
生のSQL order by式 |
limit(n) / offset(n) |
取得行数上限およびスキップ数 |
clone() |
クエリビルダーインスタンスの独立した複製を生成 |
setHashFields(fields) |
このビルダーで自動ハッシュ化するカラムをオーバーライド |
ターミナルメソッド
これらはPromiseを返し基盤となるクエリを実行します(または実行せずにコンパイルされたクエリ文字列を返します)。
| メソッド | 引数 | 戻り値 |
|---|---|---|
toSql() |
なし | string(実行せずにコンパイルされたselect SQL文字列) |
get() |
なし | 一致する行のPromise<Array<object>>(一致がない場合は[]) |
first(where?) |
オプションの{ column: value }オブジェクト |
Promise<object|null>(最初の一致行、またはnull) |
firstWhere(col, op?, val?) |
カラム名、演算子または値、オプションの値 | Promise<object|null>(最初の一致行、またはnull) |
latest(count?, column?) |
nullまたは数値、オプションのカラム名 |
countがnull: Promise<object|null>、数値count: Promise<Array<object>> |
exists() |
なし | 一致する行が存在するかどうかのPromise<boolean> |
doesntExist() |
なし | 一致する行が存在しないかどうかのPromise<boolean> |
count(column?) |
オプションのカラム名(デフォルトは*) |
Promise<number>(一致する行数。group byの場合はグループ数を返す) |
sum(column) |
カラム名 | Promise<number>(値の合計。行がない場合は0) |
avg(column) |
カラム名 | Promise<number|null>(平均値。行がない場合はnull) |
min(column) |
カラム名 | Promise<any>(最小値。行がない場合はnull) |
max(column) |
カラム名 | Promise<any>(最大値。行がない場合はnull) |
pluck(column) |
カラム名 | 一致する行全体におけるそのカラム値のPromise<Array>(一致がない場合は空の[]) |
getWithCount() |
なし | Promise<{ rows: Array<object>, total: number }>(rowsからは内部の_total_countフィールドが除外されます) |
paginate(perPage?, pageName?) |
perPage数値(デフォルト10)、オプションのpageNameクエリパラメータ文字列(デフォルト'page') |
アイテム、合計件数、ナビゲーションリンクを含むPromise<Paginator>インスタンス |
insert(data) |
行オブジェクト、または行オブジェクトの配列 | 単一行: { insertId, affectedRows, changedRows }、行の配列: affectedRowsとinsertIdを含む一括挿入ヘッダー |
update(data, where?) |
カラムと値のオブジェクト、オプションのwhereオブジェクト | Promise<object> { affectedRows, changedRows, insertId } |
increment(column, amount?, extra?, where?) |
カラム名、オプションの数値(デフォルト1)、オプションの追加カラムオブジェクト、オプションのwhereオブジェクト | Promise<object> { affectedRows, changedRows, insertId } |
decrement(column, amount?, extra?, where?) |
カラム名、オプションの数値(デフォルト1)、オプションの追加カラムオブジェクト、オプションのwhereオブジェクト | Promise<object> { affectedRows, changedRows, insertId } |
save(data) |
update(data)のエイリアス |
Promise<object> { affectedRows, changedRows, insertId } |
delete(where?) |
オプションのwhereオブジェクト(またはチェーンされたwhere) |
Promise<object> { affectedRows, changedRows, insertId }(whereが設定されていない場合はスロー) |
ビルダー自体はthenableであり非同期反復可能であるため直接await DB.table('users')やfor await (const row of DB.table('users'))を使用できます。どちらの形式もselectを実行し同じArray<object>形状を使用します。
結果の取得
すべての行の取得
getメソッドはクエリを実行し結果オブジェクトの配列を返します。
1const users = await DB.table('users').get();2// users: Array<object>. empty [] when no rows match.クエリビルダーは非同期反復可能でもありgetを呼び出さずにビルダーインスタンスを直接反復処理できます。
1for await (const user of DB.table('users')) {2 console.log(user.name);3}4// yields plain row objects (not model instances).
単一行の取得
単一行のみを取得する必要がある場合はfirstメソッドを使用します。配列でラップせずにオブジェクトを直接返します。
1const user = await DB.table('users').where('email', 'tarou@example.com').first();2// user: object | null. null when no row matches.
最新レコードの取得
latestメソッドは指定されたカラムの降順で行をソートし単一行または配列を返します。これはorderBy(column, 'DESC').limit(n).get()の短縮形です。
1const newest = await DB.table('posts').latest();2// newest: object | null3const recent = await DB.table('posts').latest(10);4// recent: Array<object>5const recentByPublished = await DB.table('posts').latest(10, 'published_at');引数なしでlatest()を呼び出すとcreated_at降順でソートされ最新の単一行(一致がない場合はnull)を返します。数値のcountを渡すとその件数の行を配列として返します。カラムのデフォルトはcreated_atですが2番目の引数でオーバーライドできます。
単一カラム値の取得(pluck)
単一カラムの値を含むフラットな配列を取得したい場合はpluckメソッドを使用します。
1const titles = await DB.table('posts').pluck('title');2// titles: Array. one entry per matching row, in the order returned by the database.
集計(count、sum、avg、min、max)
クエリビルダーはデータを集計するためのヘルパーメソッドを提供します: count、sum、avg、min、max。
1const totalOrders = await DB.table('orders').where('status', 'pending').count();2// totalOrders: number. 0 when no rows match.3 4const totalRevenue = await DB.table('orders').where('status', 'completed').sum('amount');5// totalRevenue: number. 0 when no rows match.6 7const avgPrice = await DB.table('products').where('category_id', 4).avg('price');8// avgPrice: number | null. null when no rows match.9 10const cheapest = await DB.table('products').min('price');11const priciest = await DB.table('products').max('price');すべての集計メソッドは結合されたテーブル、テーブルエイリアス、where制約を自動的に尊重します:
1const totalDuration = await DB.table('track_interactions')2 .join('tracks', 'track_interactions.track_id', '=', 'tracks.id')3 .where('track_interactions.user_id', 1)4 .where('track_interactions.type', 'like')5 .sum('tracks.duration');
select句
デフォルトではクエリビルダーはすべてのカラムを選択します。特定のカラムを指定するにはselectメソッドを使用します。
1const users = await DB.table('users').select('id', 'name', 'email').get();2// users: Array<object>. each row only carries the requested columns.select句に生のSQL式を挿入する必要がある場合は任意のバインディングとともにselectRawメソッドを使用します。
1const users = await DB.table('users')2 .selectRaw('COUNT(id) as total, status')3 .groupBy('status')4 .get();5// users: Array<object>. each row has { total, status }.クエリに重複のない結果のみを強制的に返させるにはdistinctメソッドを使用します。カラム名を指定して呼び出すとselectリストも同時に設定されます。
1const activeRoles = await DB.table('users').distinct('role').get();2// activeRoles: Array<object>. each row has the distinct role values.
サブクエリselect
selectSubメソッドを使用してselect句にサブクエリを追加できます。クロージャまたはクエリビルダーインスタンスとエイリアス名を受け取ります。
1const users = await DB.table('users')2 .select('id', 'name')3 .selectSub(q => {4 q.from('orders').selectRaw('COUNT(*)').whereColumn('orders.user_id', 'users.id');5 }, 'orders_count')6 .get();
where句
基本のwhere句
whereメソッドはカラム名、演算子、値の3つの引数を受け取ります。演算子を省略した場合ビルダーは等価(=)を前提とします。
1await DB.table('users').where('votes', '=', 100).get();2await DB.table('users').where('votes', 100).get();3await DB.table('users').where('votes', '>=', 100).get();4await DB.table('users').where('name', 'LIKE', '%test%').get();whereNotメソッドは条件を否定します。
1await DB.table('users').whereNot('status', 'inactive').get();オブジェクトを渡して複数の等価条件を同時に適用することもできます。
1await DB.table('users').where({2 status: 'active',3 role: 'admin'4}).get();
論理グループ化(whereクロージャ)
複雑なグループ化された論理式(ネストされた括弧)を作成するにはwhere、whereNot、orWhere、orWhereNotにクロージャを渡します。クロージャは制約をネストするためのクエリビルダーインスタンスを受け取ります。
1const users = await DB.table('users')2 .where('active', 1)3 .where(q => {4 q.where('role', 'admin')5 .orWhere('role', 'superadmin');6 })7 .get();8// compiles to: WHERE `active` = ? AND (`role` = ? OR `role` = ?)ネストされたクロージャをwhereNotまたはorWhereNotと組み合わせて式をNOT (式)でラップできます:
1const users = await DB.table('users')2 .where('tenant_id', 1)3 .whereNot(q => {4 q.where('status', 'banned')5 .orWhere('suspended', 1);6 })7 .get();
or文
論理OR演算子で句をチェーンするにはorWhereメソッドを使用します。
1await DB.table('users')2 .where('votes', '>', 100)3 .orWhere('name', 'tarou')4 .get();否定のOR条件にはorWhereNotメソッドも利用できます。
その他のwhere句
クエリビルダーは一般的な条件タイプのための特殊なメソッドを提供します。
whereIn / whereNotIn 指定されたカラムの値が配列内に含まれているか、またはサブクエリクロージャに一致することを検証します。
1await DB.table('users').whereIn('id', [1, 2, 3]).get();2// when the array is empty, whereIn compiles to `0 = 1` (no rows)3// and whereNotIn compiles to `1 = 1` (all rows).
whereInでのサブクエリ
whereInおよびwhereNotInにクロージャコールバックを渡してサブクエリフィルターを構築できます:
1const customersWithOrders = await DB.table('users')2 .whereIn('id', q => {3 q.from('orders').select('user_id').where('status', 'paid');4 })5 .get();6// compiles to: WHERE `id` IN (SELECT `user_id` FROM `orders` WHERE `status` = ?)whereNull / whereNotNull / orWhereNull / orWhereNotNull カラムの値がnullであること、またはnullでないことを検証します。
1await DB.table('users').whereNull('deleted_at').get();2await DB.table('users').where('status', 'active').orWhereNull('archived_at').get();3await DB.table('users').whereNotNull('verified_at').orWhereNotNull('confirmed_at').get();whereBetween / whereNotBetween / orWhereBetween / orWhereNotBetween
カラムの値が2つの境界内にあることを検証します。厳密に2つの値を含む配列を指定する必要があります。両方の値が定義されている必要があります(境界をSQLのnullのままにするにはundefinedではなくnullを使用してください)。
1await DB.table('users').whereBetween('votes', [1, 100]).get();2await DB.table('orders')3 .whereBetween('total', [50, 200])4 .orWhereBetween('total', [500, 1000])5 .get();whereRaw / orWhereRaw パラメータ化されたバインディングを使用して生のSQL where句をクエリに挿入します:
1await DB.table('orders')2 .whereRaw('price > IF(state = "tx", ?, 100)', [200])3 .orWhereRaw('status = ?', ['pending'])4 .get();
whereExistsとwhereNotExists
EXISTS (SELECT 句)サブクエリを作成するにはwhereExistsおよびwhereNotExists(または対応するorWhereExists / orWhereNotExists)を使用します:
1const users = await DB.table('users')2 .whereExists(q => {3 q.from('orders')4 .whereColumn('orders.user_id', 'users.id')5 .where('orders.total', '>', 100);6 })7 .get();
カラム間比較
同じ行内の2つの異なるカラムの値を比較するにはwhereColumnおよびorWhereColumnメソッドを使用します。
1await DB.table('users').whereColumn('updated_at', '>', 'created_at').get();2 3await DB.table('users')4 .where('status', 'active')5 .orWhereColumn('last_login_at', '>', 'created_at')6 .get();
条件分岐句(whenとunless)
特定の条件が真の場合にのみクエリ句を適用したい場合があります。メソッドチェーンを崩すことなくクエリを条件付きで変更するにはwhenおよびunlessを使用します。
whenメソッドは第1引数がtruthyと評価された場合に指定されたクロージャを実行します。オプションの第3引数のクロージャは条件がfalsyの場合に実行されます。
1const role = req.query?.role;2const sortBy = req.query?.sort;3 4const users = await DB.table('users')5 .when(role, (q, val) => q.where('role', val))6 .when(sortBy, (q, val) => q.orderBy(val, 'ASC'), q => q.orderBy('id', 'DESC'))7 .get();unlessメソッドは逆の動作をします。第1引数がfalsyの場合にクロージャを実行します。
1const users = await DB.table('users')2 .unless(includeInactive, q => q.where('active', 1))3 .get();
join(結合)
クエリビルダーは内部結合、左/右外部結合、クロス結合、生の結合式を使用した複数テーブルの結合をサポートしています。
内部結合(inner join)
基本的な内部結合を実行するにはjoinメソッドを呼び出します。対象テーブル、1番目のカラム、任意の演算子(デフォルトは=)、2番目のカラムを指定できます。
1const users = await DB.table('users')2 .join('contacts', 'users.id', '=', 'contacts.user_id')3 .select('users.*', 'contacts.phone')4 .get();引数が3つだけ渡された場合演算子はデフォルトで=になります:
1await DB.table('users')2 .join('contacts', 'users.id', 'contacts.user_id')3 .get();
左外部結合 / 右外部結合
LEFT JOINまたはRIGHT JOINを実行するにはleftJoinまたはrightJoinを使用します:
1const tracks = await DB.table('tracks')2 .leftJoin('genres', 'tracks.genre_id', '=', 'genres.id')3 .select('tracks.*', 'genres.name as genre_name')4 .get();複数の結合をチェーンしてリレーションを走査できます:
1const tracks = await DB.table('tracks')2 .leftJoin('track_artists', 'tracks.id', '=', 'track_artists.track_id')3 .leftJoin('artists', 'track_artists.artist_id', '=', 'artists.id')4 .select('tracks.*')5 .orderBy('artists.name', 'ASC')6 .get();テーブル引数ではテーブルエイリアスがサポートされています:
1await DB.table('tracks')2 .leftJoin('artists as a', 'tracks.artist_id', '=', 'a.id')3 .get();
高度な結合句
複数の結合条件を指定する必要がある場合や結合テーブルのON句とWHERE句を組み合わせる必要がある場合はjoin、leftJoin、rightJoinの第2引数としてクロージャコールバックを渡します:
1const users = await DB.table('users')2 .join('contacts', j => {3 j.on('users.id', '=', 'contacts.user_id')4 .where('contacts.primary', '=', 1)5 .whereNull('contacts.deleted_at');6 })7 .get();8// compiles to: INNER JOIN `contacts` ON `users`.`id` = `contacts`.`user_id` AND `contacts`.`primary` = ? AND `contacts`.`deleted_at` IS NULL結合句はon、orOn、where、orWhere、whereNull、whereNotNullをサポートしています。
クロス結合(cross join)
デカルト積を実行するにはcrossJoinメソッドを使用します:
1const combos = await DB.table('sizes')2 .crossJoin('colors')3 .get();
生クエリによる結合(raw joins)
複雑な結合条件や結合内でのサブクエリにはjoinRawを使用します:
1await DB.table('users')2 .joinRaw('LEFT JOIN contacts ON contacts.user_id = users.id AND contacts.status = ?', ['active'])3 .get();
ソート、グループ化、制限
orderByメソッドは結果セットをソートします。2番目の引数は方向を指定しASCまたはDESCを受け入れます。
1await DB.table('users')2 .orderBy('name', 'DESC')3 .get();groupByメソッドは結果をグループ化するための1つ以上のカラム名を受け取ります。
1await DB.table('users')2 .groupBy('account_id', 'status')3 .get();havingおよびhavingRawメソッドはグループ化された結果をフィルタリングします。論理OR条件にはorHavingおよびorHavingRawを使用します:
1await DB.table('orders')2 .groupBy('account_id')3 .having('total', '>', 500)4 .orHaving('item_count', '>=', 10)5 .get();6 7await DB.table('orders')8 .groupBy('account_id')9 .havingRaw('SUM(price) > ?', [2500])10 .orHavingRaw('COUNT(id) > ?', [50])11 .get();orderByRawメソッドは任意のソート式を可能にします:
1await DB.table('users')2 .orderByRaw('FIELD(status, "active", "pending", "banned")')3 .get();limitおよびoffsetメソッドは返されるレコード数を制限し開始位置を指定します。
1await DB.table('users')2 .offset(10)3 .limit(5)4 .get();
挿入
insertメソッドはデータベースに挿入するカラムと値のペアのオブジェクトを受け取ります。
1const result = await DB.table('users').insert({2 email: 'tarou@example.com',3 name: 'tarou'4});5// result: { insertId, affectedRows, changedRows }6// use result.insertId to read the assigned auto increment id.
一括挿入
insertメソッドにオブジェクトの配列を渡すとクエリビルダーは高度に最適化された単一の一括挿入文を実行し正規化された更新ヘッダーを返します。
1const result = await DB.table('users').insert([2 { email: 'tarou@example.com', name: 'tarou' },3 { email: 'satou@example.com', name: 'satou' }4]);5// result: { affectedRows, changedRows, insertId }6// result.affectedRows indicates total inserted rows.7// result.insertId indicates the first inserted auto increment id.
更新
updateメソッドは既存のレコードを更新します。変更するカラムとその新しい値を含むオブジェクトを受け取ります。以前にチェーンされたwhere句に一致するすべてのレコードに影響します。
1const result = await DB.table('users')2 .where('id', 1)3 .update({ votes: 1 });4// result: { affectedRows, changedRows, insertId: 0 }5// result.affectedRows tells you how many rows actually changed.update()は更新を特定のバッチ行数に制限するためにチェーンされた.limit(n)句も受け入れます:
1await DB.table('users')2 .where('status', 'pending')3 .limit(100)4 .update({ status: 'processing' });saveメソッドはupdateのエイリアスとして機能し同じ更新ヘッダーを返します。
インクリメントとデクリメント
クエリビルダーは数値カラムの値をインクリメントまたはデクリメントするための便利なメソッドも提供します。どちらのメソッドも少なくとも1つの引数(変更するカラム)を受け取ります。カラムをインクリメントまたはデクリメントする量を制御するために2番目の引数を渡すことができます(デフォルトは1)。オプションの3番目の引数を使用すると同じ文で更新する追加のカラムのオブジェクトを渡すことができます。
1// increment votes by 12await DB.table('users').where('id', 1).increment('votes');3 4// increment credits by 55await DB.table('users').where('id', 1).increment('credits', 5);6 7// increment credits by 10 and update a timestamp in the same statement8await DB.table('users').where('id', 1).increment('credits', 10, { updated_at: '2026-09-14' });9 10// decrement credits by 211await DB.table('users').where('id', 1).decrement('credits', 2);
削除
deleteメソッドはテーブルからレコードを削除します。delete()は削除を特定のバッチサイズに制限するためにチェーンされた.limit(n)句をサポートしています。
`delete()`を実行する前に少なくとも1つのwhere条件が必要です。偶発的なテーブル全削除を防ぐため制約なしで`delete()`を呼び出すと例外がスローされます。
1const result = await DB.table('users')2 .where('status', 'inactive')3 .limit(500)4 .delete();5// result: { affectedRows, changedRows, insertId: 0 }6// result.affectedRows tells you how many rows were removed.`update()`および`delete()`は`.join()`句もサポートしています。mysqlは`UPDATE`または`DELETE`文において`LIMIT`と複数テーブルの`JOIN`操作の組み合わせを禁止している点に注意してください(実行すると診断エラーがスローされます)。postgresqlおよびsqliteでは文法コンパイラが制限または結合を組み合わせた更新をテーブルの主キーに対するサブクエリ`IN`式(`WHERE id IN (SELECT id FROM テーブル)`)に自動的にコンパイルしすべてのデータベースエンジン間で一貫した動作を保証します。
クエリの複製
cloneメソッドはクエリビルダーインスタンスの独立したディープコピーを作成します。複製されたクエリはすべてのselectカラム、where句、結合定義、group byフィールド、having句、ソート条件、limit/offsetパラメータ、バインディング、ハッシュ設定を継承します。複製されたインスタンスを変更しても元のクエリには影響しません。
1const activeUsers = DB.table('users').where('status', 'active');2 3// branch query to compute total count without altering base query4const totalActive = await activeUsers.clone().count();5 6// branch query to fetch a paginated slice7const pageResults = await activeUsers.clone().limit(20).offset(0).get();
自動ハッシュ化
クエリビルダーは機密カラムを認識し挿入および更新時にbcryptを使用してその値を自動的にハッシュ化します。デフォルトではpasswordという名前のカラムのみがこの動作をトリガーします。
config/app.jsでapp.hashFields(またはカンマ区切りリストとしてのHASH_FIELDS環境変数)を使用してアプリケーション全体で自動ハッシュ化されるフィールドを宣言するかsetHashFieldsを使用して特定のクエリでオーバーライドできます。
1await DB.table('tokens')2 .setHashFields(['api_key'])3 .insert({ api_key: 'plain-text-key' });4// returns the single row insert result ({ insertId, affectedRows, changedRows }).自動カラム設定に依存せずに任意の値をハッシュ化する必要がある場合はdframeworkからエクスポートされるHashファサードを使用します。
1import { Hash } from 'dframework';2 3// uses slow, secure bcrypt (for passwords)4await DB.table('users').insert({5 custom_secret: await Hash.make('plain-text-password')6});7 8// uses fast, peppered sha256 (for indexable tokens)9await DB.table('tokens').insert({10 token_hash: Hash.fast('plain-text-token')11});カラムがハッシュフィールドとして設定されている場合はwhereHashedおよびorWhereHashedメソッドを使用して平文の値に対して直接where比較を実行することもできます。
1const token = await DB.table('tokens').whereHashed('secret', 'plain-text-key').first();2// token: object | null. whereHashed hashes the value with sha2563// and compares it against the stored hash.
