-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookshop-bookshelf.js
73 lines (63 loc) · 2.05 KB
/
bookshop-bookshelf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// --------------------------------------------------------
// Initialize knex (the query builder)
// --------------------------------------------------------
var knex = require('knex')({
client: 'postgresql',
debug: true,
connection: {
host: 'localhost',
user: '',
password: '',
database: 'demo',
charset: 'utf8'
}
});
// -----------------------------------------------------------------------------
// Initialize the ORM (knex and bookshelf)
// -----------------------------------------------------------------------------
var initializeBookshelf = require('bookshelf');
var bookshelf = initializeBookshelf(knex);
// -----------------------------------------------------------------------------
// Domain Model
// -----------------------------------------------------------------------------
// ----- Book -----
var Book = bookshelf.Model.extend({
tableName: 'books',
authors: function() {
return this.belongsToMany(Author, 'books_authors');
}
});
// ----- Author -----
var Author = bookshelf.Model.extend({
tableName: 'authors',
books: function() {
return this.belongsToMany(Book, 'books_authors');
}
});
// --------------------------------------------------------
// Get books with authors
// --------------------------------------------------------
/*
This generates two queries:
select books.* from books;
select authors.*,
books_authors.book_id as _pivot_book_id,
books_authors.author_id as _pivot_author_id
from authors
inner join books_authors on books_authors.author_id = authors.id
where books_authors.book_id in (1, 2, 3, 4);
*/
function getBooksWithAuthors() {
return new Book()
.fetchAll({
withRelated: ['authors']
});
}
// --------------------------------------------------------
// Main
// --------------------------------------------------------
getBooksWithAuthors().then(function(books) {
console.log(JSON.stringify(books, null, 4));
// close the connection
return knex.destroy();
});