Skip to content

Instantly share code, notes, and snippets.

@spro
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spro/52877b9752aff39b36eb to your computer and use it in GitHub Desktop.
Save spro/52877b9752aff39b36eb to your computer and use it in GitHub Desktop.
Bookshelf.js Examples
knex = require('knex')(client: 'pg', connection: 'postgres:///test1')
bookshelf = require('bookshelf')(knex)
util = require 'util'
inspect = (o) -> console.log util.inspect o.toJSON(), colors: true
# Schema
# ------
User = bookshelf.Model.extend
tableName: 'users'
posts: -> @hasMany Post
transactions: -> @hasMany Transaction
Post = bookshelf.Model.extend
tableName: 'posts'
user: -> @belongsTo User
Transaction = bookshelf.Model.extend
tableName: 'transactions'
user: -> @belongsTo User
# Queries
# -------
# Fetch all transactions with users attached
Transaction.fetchAll(withRelated: ['user'])
.then (transactions) -> inspect transactions
# Fetch a single user with all posts and all transactions
User.where(id: 5).fetch(withRelated: ['posts', 'transactions'])
.then (user) -> inspect user
# Fetch a single user with all posts and positive transactions
deposits = (q) -> q.where('amount', '>', 0)
User.where(id: 5).fetch(withRelated: ['posts', transactions: deposits])
.then (user) -> inspect user
select * from users;
id | name | username | email
----+-------------------------+----------------------+-------------------------------
1 | Mattie Schaden | Granville_Roberts41 | Yoshiko51@yahoo.com
2 | Frank Fahey | Lonie.Barton | Carolanne.Rau46@gmail.com
3 | Archibald Lebsack | Reynold43 | Juston_Ullrich@gmail.com
4 | Loraine Rau | Dejuan_Conn87 | Mohammad_Kuhic58@yahoo.com
5 | Ernestine Klein | German_Homenick8 | Osbaldo66@hotmail.com
6 | Adrain Waters | Pattie.Grimes | Raleigh55@gmail.com
7 | Jazmin Schoen | Kim6 | Randi27@gmail.com
8 | Naomie Stroman | Francesco_McCullough | Ludwig76@hotmail.com
9 | Noe Gottlieb | Fermin32 | Dina.Bailey@yahoo.com
10 | Leone Flatley | Germaine73 | Gabriella.Rolfson54@gmail.com
create table users {
id serial primary key,
name varchar(256),
username varchar(256),
email varchar(256)
}
create table posts {
id serial primary key,
body text,
user_id integer not null references users(id)
}
create table transactions {
id serial primary key,
summary varchar(256),
amount real,
date date,
user_id integer not null references users(id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment