-
Notifications
You must be signed in to change notification settings - Fork 122
Relationships
In order to query an object including its relationships, you can pass in its options the attribute name you want to load with the relationships:
this.datastore.findAll(Post, {
page: { size: 10, number: 1},
include: 'comments'
}).subscribe(
(document) => {
console.log(document.getMeta()); // metadata
console.log(document.getModels()); // models
}
);The same, if you want to include relationships when finding a record:
this.datastore.findRecord(Post, '1', {
include: 'comments,comments.user'
}).subscribe(
(post: Post) => console.log(post)
);The library will try to resolve relationships on infinite levels connecting nested objects by reference. So that you can have a Post, with a list of Comments, that have a User that has Posts, that have Comments... etc.
Note: If you include multiple relationships, do not use whitespaces in the include string (e.g. comments, comments.user) as those will be encoded to %20 and this results in a broken URL.
If the object you want to create has a one-to-many relationship, you can do this:
let post = this.datastore.peekRecord(Post, '1');
let comment = this.datastore.createRecord(Comment, {
title: 'My comment',
post: post
});
comment.save().subscribe();The library will do its best to discover which relationships map to one another. In the code above, for example, setting the comment relationship with the post will update the post.comments array, automatically adding the comment object!
If you want to include a relationship when creating a record to have it parsed in the response, you can pass the params object to the save() method:
comment.save({
include: 'user'
}).subscribe(
(comment: Comment) => console.log(comment)
);You can also update an object that comes from a relationship:
this.datastore.findRecord(Post, '1', {
include: 'comments'
}).subscribe(
(post: Post) => {
let comment: Comment = post.comments[0];
comment.title = 'Cool';
comment.save().subscribe((comment: Comment) => {
console.log(comment);
});
}
);