Skip to content

Commit ac05130

Browse files
committed
Merge pull request #54 from strongloop/fix-doc
Add belongsTo and hasAndBelongsToMany
2 parents 7a37969 + 4e48432 commit ac05130

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

docs/api.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,7 +641,7 @@ The express ServerResponse object. [See full documentation](http://expressjs.com
641641

642642
#### Relationships
643643

644-
##### Model.hasMany(Model)
644+
##### Model.hasMany(Model, options)
645645

646646
Define a "one to many" relationship.
647647

@@ -682,6 +682,42 @@ Book.create(function(err, book) {
682682
});
683683
});
684684
```
685+
686+
##### Model.belongsTo(Model, options)
687+
688+
A `belongsTo` relation sets up a one-to-one connection with another model, such
689+
that each instance of the declaring model "belongs to" one instance of the other
690+
model. For example, if your application includes users and posts, and each post
691+
can be written by exactly one user.
692+
693+
```js
694+
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
695+
```
696+
697+
The code above basically says Post has a reference called `author` to User using
698+
the `userId` property of Post as the foreign key. Now we can access the author
699+
in one of the following styles:
700+
701+
```js
702+
post.author(callback); // Get the User object for the post author asynchronously
703+
post.author(); // Get the User object for the post author synchronously
704+
post.author(user) // Set the author to be the given user
705+
```
706+
707+
##### Model.hasAndBelongsToMany(Model, options)
708+
709+
A `hasAndBelongsToMany` relation creates a direct many-to-many connection with
710+
another model, with no intervening model. For example, if your application
711+
includes users and groups, with each group having many users and each user
712+
appearing in many groups, you could declare the models this way,
713+
714+
```js
715+
User.hasAndBelongsToMany('groups', {model: Group, foreignKey: 'groupId'});
716+
user.groups(callback); // get groups of the user
717+
user.groups.create(data, callback); // create a new group and connect it with the user
718+
user.groups.add(group, callback); // connect an existing group with the user
719+
user.groups.remove(group, callback); // remove the user from the group
720+
```
685721
686722
#### Shared Methods
687723

0 commit comments

Comments
 (0)