forked from bookshelf/bookshelf
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.html
2898 lines (2457 loc) · 118 KB
/
index.html
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="viewport" content="width=device-width">
<link rel="canonical" href="http://bookshelfjs.org" />
<link rel="icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="docs/assets/style.css">
<link rel="stylesheet" href="docs/assets/highlight.min.css">
<title>Bookshelf.js - a JavaScript ORM for Node.js for PostgreSQL, MySQL, and SQLite3</title>
<!--
._. ._.
| | ______ _ _ _ __ | |
| | | ___ \ | | | | | |/ _| | |
| | | |_/ / ___ ___ | | _____| |__ ___| | |_ | |
| | | ___ \/ _ \ / _ \| |/ / __| '_ \ / _ \ | _| | |
| | | |_/ / (_) | (_) | <\__ \ | | | __/ | | | |
| |____\____/_\___/_\___/|_|\_\___/_|_|_|\___|_|_|_______| |
| |
\________\ /__________________________________\ /________/
\/ \/
-->
</head>
<body>
<div id="sidebar" class="interface">
<a class="toc_title" href="#">
Bookshelf.js <span class="version">(0.8.1)</span>
</a>
<ul class="toc_section">
<li>» <a href="http://github.com/tgriesser/bookshelf">GitHub Repository</a></li>
<li>» <a href="#support">Support</a></li>
<li>» <a href="#faq">FAQ</a></li>
<li>» <a href="#changelog">Change Log</a></li>
</ul>
<a class="toc_title" href="#introduction">
Introduction
</a>
<a class="toc_title" href="#installation">
Installation
</a>
<a class="toc_title" href="#Model">
Model
</a>
<ul class="toc_section">
<li>– <i><a href="#Model-extend">extend</a></i></li>
<li>– <i><a href="#Model-forge">forge</a></i></li>
<li>– <i><a href="#Model-collection">collection</a></i></li>
<li>– <a href="#Model-constructor">constructor / initialize</a></li>
<li>– <a href="#Model-tableName">tableName</a></li>
<li>– <a href="#Model-idAttribute">idAttribute</a></li>
<li>– <a href="#Model-id">id</a></li>
<li>– <a href="#Model-set">set</a></li>
<li>– <a href="#Model-get">get</a></li>
<li>– <a href="#Model-refresh">refresh</a></li>
<li>– <a href="#Model-fetch">fetch</a></li>
<li>– <a href="#Model-fetchAll">fetchAll</a></li>
<li>– <a href="#Model-count">count</a></li>
<li>– <a href="#Model-where">where</a></li>
<li>– <a href="#Model-query">query</a></li>
<li>– <a href="#Model-load">load</a></li>
<li><b><a href="#Model-relation-types">Relation Types:</a></b></li>
<li>– <a href="#Model-hasOne">hasOne</a></li>
<li>– <a href="#Model-hasMany">hasMany</a></li>
<li>– <a href="#Model-belongsTo">belongsTo</a></li>
<li>– <a href="#Model-belongsToMany">belongsToMany</a></li>
<li>- <a href="#Model-through">through</a></li>
<li> - <a href="#Model-attach">attach</a></li>
<li> - <a href="#Model-detach">detach</a></li>
<li> - <a href="#Model-withPivot">withPivot</a></li>
<li> - <a href="#Model-updatePivot">updatePivot</a></li>
<li><b><a href="#Model-polymorphic-associations">Polymorphic Associations:</a></b></li>
<li> – <a href="#Model-morphOne">morphOne</a></li>
<li> – <a href="#Model-morphMany">morphMany</a></li>
<li> – <a href="#Model-morphTo">morphTo</a></li>
<li>– <a href="#Model-relations">relations</a></li>
<li>– <a href="#Model-related">related</a></li>
<li>– <a href="#Model-relatedData">relatedData</a></li>
<li>– <a href="#Model-save">save</a></li>
<li>– <a href="#Model-destroy">destroy</a></li>
<li>– <a href="#Model-format">format</a></li>
<li>– <a href="#Model-parse">parse</a></li>
<li>– <a href="#Model-toJSON">toJSON</a></li>
<li>– <a href="#Model-Backbone-Methods"><b>Other Backbone Methods (4)</b></a></li>
<li>– <a href="#Model-Underscore-Methods"><b>Underscore Methods (6)</b></a></li>
<li>– <a href="#Model-where">where</a></li>
<li>– <a href="#Model-query">query</a></li>
<li>– <a href="#Model-resetQuery">resetQuery</a></li>
<li>– <a href="#Model-hasTimestamps">hasTimestamps</a></li>
<li>– <a href="#Model-timestamp">timestamp</a></li>
<li>– <a href="#Model-defaults">defaults</a></li>
<li>– <a href="#Model-isNew">isNew</a></li>
<li>– <a href="#Model-hasChanged">hasChanged</a></li>
<li>– <a href="#Model-previous">previous</a></li>
<li>– <a href="#Model-previousAttributes">previousAttributes</a></li>
<li>– <a href="#Model-sync">sync</a></li>
</ul>
<a class="toc_title" href="#Associations">
Associations
</a>
<ul class="toc_section">
<li>– <a href="#Associations-one-to-one">One-to-one</a></li>
<li>– <a href="#Associations-one-to-many">One-to-many</a></li>
<li>– <a href="#Associations-many-to-many">Many-to-many</a></li>
</ul>
<a class="toc_title" href="#Collection">
Collection
</a>
<ul class="toc_section">
<li>– <i><a href="#Collection-extend">extend</a></i></li>
<li>– <i><a href="#Collection-forge">forge</a></i></li>
<li>– <a href="#Collection-model">model</a></li>
<li>– <a href="#Collection-constructor">constructor / initialize</a></li>
<li>– <a href="#Collection-models">models</a></li>
<li>– <a href="#Collection-parse">parse</a></li>
<li>– <a href="#Collection-toJSON">toJSON</a></li>
<li>– <a href="#Collection-fetch">fetch</a></li>
<li>– <a href="#Collection-fetchOne">fetchOne</a></li>
<li>– <a href="#Collection-count">count</a></li>
<li>– <a href="#Collection-mapThen">mapThen</a></li>
<li>– <a href="#Collection-invokeThen">invokeThen</a></li>
<li>– <a href="#Collection-load">load</a></li>
<li>– <a href="#Collection-add">add</a></li>
<li>– <a href="#Collection-remove">remove</a></li>
<li>– <a href="#Collection-reset">reset</a></li>
<li>– <a href="#Collection-set">set</a></li>
<li>– <a href="#Collection-get">get</a></li>
<li>– <a href="#Collection-at">at</a></li>
<li>– <a href="#Collection-query">query</a></li>
<li>– <a href="#Collection-resetQuery">resetQuery</a></li>
<li>– <a href="#Collection-sync">sync</a></li>
<li>– <a href="#Collection-create">create</a></li>
<li>– <a href="#Collection-Backbone-Methods"><b>Other Backbone Methods (12)</b></a></li>
<li>– <a href="#Collection-Underscore-Methods"><b>Underscore Methods (28)</b></a></li>
</ul>
<a class="toc_title" href="#Events">
Events
</a>
<ul class="toc_section">
<li>– <a href="#Events-Backbone-Methods"><b>Backbone Methods (5)</b></a></li>
<li>– <a href="#Events-triggerThen">triggerThen</a></li>
<li>- <a href="#Events-catalog"><b>Catalog of Built-in Events</b></a></li>
</ul>
<a class="toc_title" href="#Utility">
Utility
</a>
<ul class="toc_section">
<li>– <a href="#Bookshelf-knex">bookshelf.knex</a></li>
<li>– <a href="#Bookshelf-transaction">bookshelf.transaction</a></li>
</ul>
<a class="toc_title" href="#Plugins">
Plugins
</a>
<ul class="toc_section">
<li>– <a href="#Plugins-Registry">Registry</a></li>
<li>– <a href="#Plugins-Visibility">Visibility</a></li>
<li>– <a href="#Plugins-Virtuals">Virtuals</a></li>
</ul>
<a class="toc_title" href="#faq">
F.A.Q.
</a>
<a class="toc_title" href="#changelog">
Change Log
</a>
</div>
<a href="https://github.com/tgriesser/bookshelf"><img style="position: fixed; top: 0; right: 0; border: 0;" src="docs/images/github.png" alt="Fork me on GitHub"></a>
<div class="container">
<p>
<img id="logo" src="docs/images/bookshelf.png" alt="Bookshelf.js">
</p>
<p>
<b>Bookshelf</b> is a JavaScript ORM for Node.js, built on the <a href="http://knexjs.org">Knex</a> SQL query builder. Featuring both <a href="http://promises-aplus.github.com/promises-spec/">promise based</a> and <a href="#faq-callbacks">traditional callback</a> interfaces, it follows the Model & Collection patterns seen in Backbone.js, providing <a href="#Bookshelf-transaction">transaction support</a>,
eager/nested-eager relation loading, <a href="#Model-polymorphic-associations">polymorphic associations</a>, and support for
<a href="#Associations-one-to-one">one-to-one</a>, <a href="#Associations-one-to-many">one-to-many</a>, and <a href="#Associations-many-to-many">many-to-many</a> relations.
</p>
<p>
It is designed to work well with <b>PostgreSQL</b>, <b>MySQL</b>, and <b>SQLite3</b>.
</p>
<p>
The project is <a href="http://github.com/tgriesser/bookshelf/">hosted on GitHub</a>,
and has a comprehensive <a href="https://travis-ci.org/tgriesser/bookshelf">test suite</a>.
</p>
<h2>Latest Release: 0.8.2 - <span class="small"><a href="#changelog">Change Log</a></span></h2>
<p>
Current Develop —
<a href="https://travis-ci.org/tgriesser/bookshelf">
<img src="https://travis-ci.org/tgriesser/bookshelf.png?branch=master" alt="Travis Badge">
</a>
</p>
<p>
Bookshelf is available for use under the <a href="http://github.com/tgriesser/bookshelf/blob/master/LICENSE">MIT software license</a>.
</p>
<p>
You can report bugs and discuss features on the
<a href="http://github.com/tgriesser/bookshelf/issues">GitHub issues page</a>,
add pages to the <a href="https://github.com/tgriesser/bookshelf/wiki">wiki</a>
or send tweets to <a href="http://twitter.com/tgriesser">@tgriesser</a>.
</p>
<h2 id="introduction">Introduction</h2>
<p>
Bookshelf aims to provide a simple library for common tasks when querying databases in JavaScript,
and forming relations between these objects, taking a lot of ideas from the
the <a href="http://en.wikipedia.org/wiki/Data_mapper_pattern">Data Mapper Pattern</a>.
With a concise, literate codebase, Bookshelf is simple to read, understand, and extend.
It doesn't force you to use any specific validation scheme,
provides flexible and efficient relation/nested-relation loading, and first class transaction support.
It's a lean Object Relational Mapper, allowing you to drop down to the raw knex interface whenever you need a custom query that doesn't quite fit with the stock conventions.
</p>
<p>
Bookshelf follows the excellent foundation provided by Backbone.js Models and Collections,
using similar patterns, naming conventions, and philosophies to build a lightweight,
easy to navigate ORM. If you know how to use Backbone, you probably already know how
to use Bookshelf.
</p>
<h2 id="installation">Installation</h2>
<p>
You'll need to install a copy of <a href="http://knexjs.org">knex.js</a>, and either <tt>mysql</tt>,
<tt>pg</tt>, or <tt>sqlite3</tt> from npm.
</p>
<pre>
$ npm install knex --save
$ npm install bookshelf --save
# Then add one of the following:
$ npm install pg
$ npm install mysql
$ npm install mariasql
$ npm install sqlite3
</pre>
<p>
The Bookshelf library is initialized by passing an initialized
<a href="http://knexjs.org">Knex</a> client instance.
The <a href="http://knexjs.org">knex documentation</a> provides a number of examples for different databases.
</p>
<pre><code>
var knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users'
});
</code></pre>
<p>
This initialization should likely only ever happen once in your application, as it creates a connection pool for the current database, you should use the <tt>bookshelf</tt> instance returned throughout your library.
You'll need to store this instance created by the initialize somewhere in the application you can reference it. A common pattern to follow is to initialize the client in a module so you can easily reference it later:
</p>
<pre><code>
// In a file named something like bookshelf.js
var knex = require('knex')(dbConfig);
module.exports = require('bookshelf')(knex);
// elsewhere, to use the bookshelf client:
var bookshelf = require('./bookshelf');
var Post = bookshelf.Model.extend({
// ...
});
</code></pre>
<h2 id="Model">Bookshelf Models</h2>
<p>
<b>Models</b> are simple objects representing individual database rows, specifying the
<a href="#Model-tableName">tableName</a> and any <a href="#Model-relation-types">relations</a>
to other models. They can be <a href="#Model-extend">extended</a> with any domain-specific methods,
which can handle components such as validations, computed properties, and access control.
</p>
<p id="Model-extend">
<b class="header">extend</b><code>bookshelf.Model.extend([protoProps], [classProperties])</code>
<br />
To create a <b>Model</b> class of your own, you extend <b>bookshelf.Model</b>
and provide instance <b>properties</b>, as well as optional
<b>classProperties</b> to be attached directly to the constructor function.
</p>
<p>
<b>extend</b> correctly sets up the prototype chain, so subclasses created
with <b>extend</b> can be further extended and subclassed as far as you like.
</p>
<pre><code>
var checkit = require('checkit');
var Promise = require('bluebird');
var bcrypt = Promise.promisifyAll(require('bcrypt'));
var Customer = bookshelf.Model.extend({
initialize: function() {
this.on('saving', this.validateSave);
},
validateSave: function() {
return checkit(rules).run(this.attributes);
},
account: function() {
return this.belongsTo(Account);
},
}, {
login: Promise.method(function(email, password) {
if (!email || !password) throw new Error('Email and password are both required');
return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(function(customer) {
return bcrypt.compareAsync(customer.get('password'), password);
});
})
});
Customer.login(email, password)
.then(function(customer) {
res.json(customer.omit('password'));
}).catch(Customer.NotFoundError, function() {
res.json(400, {error: email + ' not found'});
}).catch(function(err) {
console.error(err);
});
</code></pre>
<p class="warning">
Brief aside on <tt>super</tt>: JavaScript does not provide
a simple way to call super — the function of the same name defined
higher on the prototype chain. If you override a core function like
<tt>set</tt>, or <tt>save</tt>, and you want to invoke the
parent object's implementation, you'll have to explicitly call it, along these lines:
</p>
<pre><code>
var Customer = bookshelf.Model.extend({
set: function() {
...
bookshelf.Model.prototype.set.apply(this, arguments);
...
}
});
</code></pre>
<p id="Model-forge">
<b class="header">forge</b><code>bookshelf.Model.forge([attributes], [options])</code>
<br />
A simple helper function to instantiate a new <tt>Model</tt> without needing <tt>new</tt>.
</p>
<pre><code>
var Customer = bookshelf.Model.extend({
tableName: 'customers'
});
Customer.forge({item: 'value'}).save().then(function() {
// ...
});
</code></pre>
<p id="Model-collection">
<b class="header">collection</b><code>Model.collection([models], [options])</code>
<br />
A simple static helper to instantiate a new <a href="#Collection">Collection</a>, setting the current model as the collection's target.
</p>
<pre><code>
Customer.collection().fetch().then(function(collection) {
// ...
})
</code></pre>
<p id="Model-constructor">
<b class="header">constructor / initialize</b><code>new Model([attributes], [options])</code>
<br />
When creating an instance of a model, you can pass in the initial values
of the <b>attributes</b>, which will be <a href="#Model-set">set</a> on the
model. If you define an <b>initialize</b> function, it will be invoked when
the model is created.
</p>
<pre><code>
new Book({
title: "One Thousand and One Nights",
author: "Scheherazade"
});
</code></pre>
<p>
In rare cases, if you're looking to get fancy,
you may want to override <b>constructor</b>, which allows
you to replace the actual constructor function for your model.
</p>
<pre><code>
var Books = bookshelf.Model.extend({
tableName: 'documents',
constructor: function() {
bookshelf.Model.apply(this, arguments);
this.on('saving', function(model, attrs, options) {
options.query.where('type', '=', 'book');
});
}
});
</code></pre>
<p>
The <tt>tableName</tt> and <tt>hasTimestamps</tt> properties
will be directly attached if passed in the <b>options</b> during model creation.
</p>
<p>
If <tt>{parse: true}</tt> is passed as an <b>option</b>, the <b>attributes</b>
will first be converted by <a href="#Model-parse">parse</a> before being
<a href="#Model-set">set</a> on the model.
</p>
<p id="Model-tableName">
<b class="header">tableName</b><code>model.tableName</code>
<br />
A required property for any database usage, The <b>tableName</b> property
refers to the database table name the model will query against.
</p>
<pre><code>
var Television = bookshelf.Model.extend({
tableName: 'televisions'
});
</code></pre>
<p id="Model-idAttribute">
<b class="header">idAttribute</b><code>model.idAttribute</code>
<br />
This tells the model which attribute to expect as
the unique identifier for each database row
(typically an auto-incrementing primary key named <b>id</b>).
Note that if you are using <b>parse</b> and <b>format</b>
(to have your model's attributes in <tt>camelCase</tt>,
but your database's columns in <tt>snake_case</tt>, for example)
this refers to the name returned by <b>parse</b> (<tt>myId</tt>),
not the database column (<tt>my_id</tt>). Specify compound primary
keys as an array of columns.
</p>
<p id="Model-id">
<b class="header">id</b><code>model.id</code>
<br />
A special property of models, the <b>id</b> is the unique identifier associated,
named by the <a href="#Model-idAttribute">idAttribute</a>. If you set the <b>id</b>
in the attributes hash, it will be copied onto the model as a direct property.
Models can be retrieved by id from collections, and the id is used in fetching models and
building model relations.
</p>
<p id="Model-set">
<b class="header">set</b><code>model.set(attributes, [options])</code>
<br />
Set a hash of attributes (one or many) on the model. If any of the attributes
change the model's state, a <tt>"change"</tt> event will be triggered. You may also pass individual keys and values.
</p>
<pre><code>
customer.set({first_name: "Joe", last_name: "Customer"});
customer.set("telephone", "555-555-1212");
</code></pre>
<p id="Model-get">
<b class="header">get</b><code>model.get(attribute)</code>
<br />
Get the current value of an attribute from the model. For example:
<tt>note.get("title")</tt>
</p>
<p id="Model-refresh">
<b class="header">refresh</b><code>model.refresh([options]).then(function(model) {...</code>
<p>
Updates model attributes to match those currently in the database. If the model's <tt><a href="#Model-idAttribute">idAttribute</a></tt> is set, then it will do a <tt>select</tt> based on primary key alone. Otherwise it will default to <tt><a href="#Model-fetch">fetch</a></tt>'s behaviour of matching all given <tt><a href="#Model-attributes">attributes</a></tt>.
</p>
<p>
Accepts the same options as <tt><a href="#Model-fetch">fetch</a></tt>; <tt>{require: true}</tt> to throw an error if the model is not found, and <tt>{columns: [...]}</tt> to only update certain columns.
</p>
</p>
<p id="Model-fetch">
<b class="header">fetch</b><code>model.fetch([options]).then(function(model) {...</code>
<br />
Fetches a model from the database, using <em>all</em> attributes currently set on the model
to form a <tt>select</tt> query. Returns a promise, which will resolve with the fetched <tt>model</tt>,
or <tt>undefined</tt> if the model isn't fetched. If you wish to trigger an error if the fetched model is not found, pass <tt>{require: true}</tt> as one of the options to the fetch call. A <tt>"fetching"</tt> event will be fired just before the record is fetched; a good place to hook into for validation. A <tt>"fetched"</tt> event will be fired when a record is successfully retrieved. If you need to constrain the query performed by fetch, you can call the <a href="#Model-query">query</a> method before calling fetch.
</p>
<pre><code>
// select * from `books` where `ISBN-13` = '9780440180296'
new Book({'ISBN-13': '9780440180296'})
.fetch()
.then(function(model) {
// outputs 'Slaughterhouse Five'
console.log(model.get('title'));
});
</code></pre>
<p class="warning">
If you'd like to only fetch specific columns, you may specify a <tt>columns</tt> property,
in the <tt>options</tt> for the fetch call, or use the <a href="#Model-query">query</a> method,
tapping into the knex <a href="http://knexjs.org/#Builder-column">column</a> method to specify which columns will be fetched.
</p>
<p>
The <tt>withRelated</tt> parameter may be specified to fetch the resource,
along with any specified <a href="#Model-relations">relations</a> named on the model.
A single property, or an array of properties can be specified as a value for the <tt>withRelated</tt>
property. The results of these relation queries will be loaded into a <tt>relations</tt> property on
the model, may be retrieved with the <a href="#Model-related">related</a> method, and will
be serialized as properties on a <a href="#Model-toJSON">toJSON</a> call unless
<tt>{shallow: true}</tt> is passed.
</p>
<pre><code>
var Book = bookshelf.Model.extend({
tableName: 'books',
editions: function() {
return this.hasMany(Edition);
},
genre: function() {
return this.belongsTo(Genre);
}
})
new Book({'ISBN-13': '9780440180296'}).fetch({
withRelated: ['genre', 'editions']
}).then(function(book) {
console.log(book.related('genre').toJSON());
console.log(book.related('editions').toJSON());
console.log(book.toJSON());
});
</code></pre>
<p id="Model-fetchAll">
<b class="header">fetchAll</b><code>Model.fetchAll / model.fetchAll([options]).then(function(collection) {...</code>
<br />
Fetches a <a href="#Collection">collection</a> of models from the database, using any <a href="#Model-query">query</a> parameters currently set on the model to form a <tt>select</tt> query. Returns a promise, which will resolve with the fetched <tt>collection</tt>. If you wish to trigger an error if no models are found, pass <tt>{require: true}</tt> as one of the options to the fetchAll call. A <tt>"fetching"</tt> event will be fired just before the collection is fetched; a good place to hook into for validations. A <tt>"fetched"</tt> event will be fired when a record is successfully retrieved. If you need to constrain the query performed by fetch, you can call the <a href="#Model-query">query</a> method before calling fetch.
</p>
<p id="Model-count">
<b class="header">count</b><code>Model.count / model.count(column='*', [options]).then(function(count) { ...</code>
<br>
Gets the number of matching records in the database, respecting any previous calls to <a href="#Model-query">query</a>. If a <tt>column</tt> if provided, records with a null value in that column will be excluded from the count.
<pre><code>
// Get the number of named, blue ducks.
Duck.where('color', 'blue').count('name')
.then(function(count) { //...
</code></pre>
<p id="Model-load">
<b class="header">load</b><code>model.load(relations, [options]).then(function(model) {...</code>
<br />
The <b>load</b> method takes an array of <b>relations</b> to eager load attributes onto a Model,
in a similar way that the <tt>withRelated</tt> property works on fetch. Dot separated attributes
may be used to specify deep eager loading.
</p>
<pre><code>
new Posts().fetch().then(function(collection) {
collection.at(0)
.load(['author', 'content', 'comments.tags'])
.then(function(model) {
JSON.stringify(model);
});
});
{
title: 'post title',
author: {...},
content: {...},
comments: [
{tags: [...]}, {tags: [...]}
]
}
</code></pre>
<h3 id="Model-relation-types">Relation Types:</h3>
<p>
Relationships are used to create <a href="#Associations">associations between models</a>.
</p>
<p>
There are four types of relationships that may be defined between Models and
Collections: <a href="#Model-hasOne">hasOne</a>, <a href="#Model-hasMany">hasMany</a>,
<a href="#Model-belongsTo">belongsTo</a>, <a href="#Model-belongsToMany">belongsToMany</a>.
The relations are specified by creating named methods on the model, which return the
appropriate relation type.
</p>
<pre><code>
var Summary = bookshelf.Model.extend({tableName: 'summaries'});
var Author = bookshelf.Model.extend({tableName: 'authors'});
var Owner = bookshelf.Model.extend({tableName: 'owners'});
var Pages = bookshelf.Model.extend({tableName: 'pages'});
var Book = bookshelf.Model.extend({
summary: function() {
return this.hasOne(Summary);
},
owner: function() {
return this.belongsTo(Owner);
},
pages: function() {
return this.hasMany(Pages);
},
author: function() {
return this.belongsToMany(Author);
}
});
new Book({id: 1}).related('summary').fetch().then(function(summary) {
console.log(summary.toJSON());
});
// or:
new Book({id: 1}).summary().fetch().then(function(summary) {
console.log(summary.toJSON());
});
</code></pre>
<p>
Relations may also be loaded eagerly, by specifying a <tt>withRelated</tt> option
during the fetch call. Note that the call to related will successfully return an object regardless of whether or not such a
relation exists. To check for the existence of a related object, use the id.
</p>
<pre><code>
new Book({id: 2}).fetch({
withRelated: ['summary', 'owner', 'pages', 'author']
}).then(function(book) {
console.log(book.toJSON());
var owner = book.related('owner');
if (owner.id) {
console.log(owner.toJSON());
}
});
</code></pre>
<p>
You may also want to eagerly load related models on a model or collection after it has already been fetched.
For this, you may use the <a href="#Model-load">load</a> method to specify which relations should be eagerly
loaded on the model or collection.
</p>
<pre><code>
var accounts = new Accounts();
accounts.fetch()
.then(function(collection) {
return collection.at(0).load('account_info');
})
.then(function(model) {
res.json({
accounts: accounts.toJSON({shallow: true}),
current_account: model
});
});
</code></pre>
<p>
Nested eager loads may be performed, by separating the nested relations with <tt>'.'</tt>.
</p>
<pre><code>
Story.where({id: 2}).fetch({
withRelated: ['comments.tags', 'comments.author', 'author']
}).then(function(model) {
JSON.stringify(model);
});
// performs 5 queries in total, outputting:
{
id: 2,
title: '',
author: {...},
comments: [
{tags: [{...}, {...}], author: {...}},
{tags: [...], author: {...}},
{tags: [...], author: {...}}
]
}
</code></pre>
<p>
An object may be passed as a relation, where the first argument is the key and the second a function
which constraints the relation, called with the context of the current related model and accepting the
Knex query builder object as the first argument.
</p>
<pre><code>
Story.where({id: 2}).fetch({
withRelated: ['comments.tags', 'comments.author', {
'author': function(qb) {
qb.where('status', 'active')
}
}]
}).then(...
</code></pre>
<p id="Model-hasOne">
<b class="header">hasOne</b><code>model.hasOne(Target, [foreignKey])</code>
<br />
A one-to-one relation is a very basic relation, where the <b>model</b> has exactly
one of another <b>Target</b> model, referenced by a <b>foreignKey</b> in the <b>Target</b> model.
By default, the <b>foreignKey</b> is assumed to be the singular form of the current model's <a href="#Model-tableName">tableName</a>,
followed by <tt>_id</tt> / <tt>_{{idAttribute}}</tt>.
</p>
<pre><code>
var Record = bookshelf.Model.extend({
tableName: 'health_records'
});
var Patient = bookshelf.Model.extend({
tableName: 'patients',
record: function() {
return this.hasOne(Record);
}
});
// select * from `health_records` where `patient_id` = 1;
new Patient({id: 1}).related('record').fetch().then(function(model) {
...
});
// alternatively, if you don't need the relation loaded on the patient's relations hash:
new Patient({id: 1}).record().fetch().then(function(model) {
...
});
</code></pre>
<p>
If the foreign key is different than the one assumed by the query builder, you may specify
it in the second argument of the query.
</p>
<p id="Model-hasMany">
<b class="header">hasMany</b><code>model.hasMany(Target, [foreignKey])</code>
<br />
Typically the most common relationship type, a <tt>hasMany</tt> is when the <b>model</b>
has a "one-to-many" relationship with the <b>Target</b> model or collection. The
<b>model</b> is referenced by a <b>foreignKey</b> in the <b>Target</b> model, which defaults to the singular form of the current model's
<a href="#Model-tableName">tableName</a>, followed by <tt>_id</tt> / <tt>_{{idAttribute}}</tt>.
</p>
<p id="Model-belongsTo">
<b class="header">belongsTo</b><code>model.belongsTo(Target, [foreignKey])</code>
<br />
The <tt>belongsTo</tt> relationship is used when a <b>model</b> is a member of another <b>Target</b> model. It can be used in a
<a href="#Associations-one-to-one">one-to-one</a> associations as the inverse of a <a href="#Model-hasOne">hasOne</a>. It can also be used in
<a href="#Associations-one-to-many">one-to-many</a> associations as the inverse of a <a href="#Model-hasMany">hasMany</a>
(and is the <i>one</i> side of that association). In both cases, the <tt>belongsTo</tt>
relationship is used for a <b>model</b> that is a member of another <b>Target</b> model, referenced by the <b>foreignKey</b> in the current <b>model</b>.
By default, the <b>foreignKey</b> is assumed to be the singular form of the <b>Target</b> model's <a href="#Model-tableName">tableName</a>,
followed by <tt>_id</tt> / <tt>_{{idAttribute}}</tt>.
</p>
<pre><code>
var Book = bookshelf.Model.extend({
tableName: 'books',
author: function() {
return this.belongsTo(Author);
}
});
// select * from `books` where id = 1
// select * from `authors` where id = book.author_id
Book.where({id: 1}).fetch({withRelated: ['author']}).then(function(book) {
console.log(JSON.stringify(book.related('author')));
});
</code></pre>
<p id="Model-belongsToMany">
<b class="header">belongsToMany</b><code>model.belongsToMany(Target, [table], [foreignKey], [otherKey])</code>
<br />
The <tt>belongsToMany</tt> method defines a many-to-many relation, where the current <b>model</b>
is joined to one or more of a <b>Target</b> model through another <b>table</b>. The default name for
the joining table is the two table names, joined by an underscore, ordered alphabetically. For example, a
<tt>users</tt> table and an <tt>accounts</tt> table would have a joining table of <tt>accounts_users</tt>.
<pre><code>
var Account = bookshelf.Model.extend({
tableName: 'accounts'
});
var User = bookshelf.Model.extend({
tableName: 'users',
allAccounts: function () {
return this.belongsToMany(Account);
},
adminAccounts: function() {
return this.belongsToMany(Account).query({where: {access: 'admin'}});
},
viewAccounts: function() {
return this.belongsToMany(Account).query({where: {access: 'readonly'}});
}
});
</code></pre>
<p>
The default key names in the joining table are the singular versions of the model table names, followed by <tt>_id</tt> / <tt>_{{idAttribute}}</tt>.
So in the above case, the columns in the joining table would be <tt>user_id</tt>, <tt>account_id</tt>, and
<tt>access</tt>, which is used as an example of how dynamic relations can be formed using different contexts. To
customize the keys used in, or the <tt>tableName</tt> used for the join table, you may specify them like so:
</p>
<pre><code>
this.belongsToMany(Account, 'users_accounts', 'userid', 'accountid');
</code></pre>
<p>
If you wish to create a <tt>belongsToMany</tt> association where the joining table has a primary key, and
more information about the model, you may create a belongsToMany <a href="#Model-through">through</a> relation:
</p>
<pre><code>
var Doctor = bookshelf.Model.extend({
patients: function() {
return this.belongsToMany(Patient).through(Appointment);
}
});
var Appointment = bookshelf.Model.extend({
patient: function() {
return this.belongsTo(Patient);
},
doctor: function() {
return this.belongsTo(Doctor);
}
});
var Patient = bookshelf.Model.extend({
doctors: function() {
return this.belongsToMany(Doctor).through(Appointment);
}
});
</code></pre>
<p id="Model-through">
<b class="header">through</b><code>.through(JoinModel, [throughFk], [otherKey])</code>
<br />
The <tt>through</tt> method helps to create dynamic relations between models & collections, where a
<a href="#Model-hasOne">hasOne</a>, <a href="#Model-hasMany">hasMany</a>, <a href="#Model-belongsTo">belongsTo</a>,
or <a href="#Model-belongsToMany">belongsToMany</a> relation may run <tt>through</tt> a <b>JoinModel</b>.
</p>
<p>
A good example of where this would be useful is if a book <tt>hasMany</tt> paragraphs <tt>through</tt>
chapters. Consider the following examples:
</p>
<pre><code>
var Book = bookshelf.Model.extend({
tableName: 'books',
// Find all paragraphs associated with this book, by
// passing through the "Chapter" model.
paragraphs: function() {
return this.hasMany(Paragraph).through(Chapter);
},
chapters: function() {
return this.hasMany(Chapter);
}
});
var Chapter = bookshelf.Model.extend({
tableName: 'chapters',
paragraphs: function() {
return this.hasMany(Paragraph);
}
});
var Paragraph = bookshelf.Model.extend({
tableName: 'paragraphs',
chapter: function() {
return this.belongsTo(Chapter);
},
// A reverse relation, where we can get the book from the chapter.
book: function() {
return this.belongsTo(Book).through(Chapter);
}
});
</code></pre>
<p>
The "through" table creates a pivot model, which it assigns to <tt>model.pivot</tt> after it is created.
On <tt>toJSON</tt>, the pivot model is flattened to values prefixed with <tt>_pivot_</tt>.
</p>
<p id="Model-attach">
<b class="header">attach</b><code>relation.attach(ids, [options])</code>
<br />
Attaches one or more <b>ids</b> from a foreign table to the current table, in a
<a href="#Model-belongsToMany">belongsToMany</a> relationship.
Creates & saves a new model and attaches the model with the related model.
</p>
<pre><code>
new Site({id: 1}).related('admins').attach([1, 2]);
</code></pre>
<p>
The attach function may also take one or more models to attach to the current
model:
</p>
<pre><code>
var admin1 = new Admin({username: 'user1', password: 'test'});
var admin2 = new Admin({username: 'user2', password: 'test'});
Promise.all([admin1.save(), admin2.save()])
.then(function() {
return Promise.all([
new Site({id: 1}).admins().attach([admin1, admin2]),
new Site({id: 2}).admins().attach(admin2)
]);
})
</code></pre>
<p id="Model-detach">
<b class="header">detach</b><code>relation.detach(ids, [options])</code>
<br />
Detach one or more related objects from their pivot tables. If a model or id is passed,