Référence rapide

Aide-mémoire Bookshelf.js ORM pour Node.js

Guide de référence rapide pour Bookshelf.js ORM dans Node.js : définition des modèles, associations, horodatages et opérations CRUD.

· Publié le

Bookshelf.js est un ORM JavaScript pour Node.js basé sur le constructeur de requêtes Knex SQL, prenant en charge PostgreSQL, MySQL et SQLite3.

Définition de modèle (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 et relations (Associations & Relations)

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

Opérations CRUD et requêtes

// 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();

Aide-mémoires connexes

Sujets associés