クイックリファレンス

Bookshelf.js ORM チートシート(Node.js)

Node.js の JavaScript ORM Bookshelf.js クイックリファレンス。モデル定義、リレーション、タイムスタンプ、CRUD クエリを網羅。

· 公開日

Bookshelf.js は、Knex SQL クエリビルダー上に構築された Node.js 向け JavaScript ORM であり、PostgreSQL、MySQL、SQLite3 をサポートしています。

モデル定義(Model Definition)

const knex = require('knex')(require('./knexfile'));
const bookshelf = require('bookshelf')(knex);

const Summary = bookshelf.Model.extend({
  tableName: 'summaries',
  hasTimestamps: true, // enables 'created_at' and 'updated_at'
  // Or specify custom column names:
  // hasTimestamps: ['created_on', 'updated_on']
});

アソシエーションとリレーション(Associations & Relations)

const Book = bookshelf.Model.extend({
  tableName: 'books',
  summary() {
    return this.hasOne(Summary);
  },
  author() {
    return this.belongsTo(Author);
  },
  genres() {
    return this.belongsToMany(Genre);
  }
});

CRUD 操作とクエリ実行

// Create & Save
const book = new Book({ title: 'Design Patterns', pages: 395 });
await book.save();

// Or create shortcut
await Book.forge({ title: 'Refactoring' }).save();
// Fetch & Querying
// Fetch single record by primary key
const book = await new Book({ id: 1 }).fetch();

// Filtering with attributes
const redBooks = await Book.where({ favorite_color: 'red' }).fetchAll();

// Knex query builder integration
const recentBooks = await Book.query((qb) => {
  qb.where('pages', '>', 200).orderBy('created_at', 'desc');
}).fetchAll();

関連するチートシート

関連テーマ