Skip to content

Commit 5ba1a44

Browse files
committed
chore: update readme
1 parent 581c29d commit 5ba1a44

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

README.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,90 @@ await this.posts.comments().attach(payload)
517517
await this.posts.comments().sync(payload)
518518
```
519519

520+
You can also apply a model instance to a nested object by setting the key and the model in `relations` method.
521+
522+
If the backend responds with:
523+
524+
```js
525+
// response from API for /posts/1
526+
{
527+
title: 'My title'
528+
body: 'Some text here',
529+
user: {
530+
firstName: 'John',
531+
lastName: 'Doe'
532+
}
533+
}
534+
```
535+
536+
We just need to set `user` to User model:
537+
538+
539+
**/models/Post.js**
540+
```js
541+
class Post extends Model {
542+
relations () {
543+
return {
544+
// Apply User model to `user` object
545+
user: User
546+
}
547+
}
548+
}
549+
```
550+
551+
It also works for collections. So if the backend responds with:
552+
553+
```js
554+
// response from API for /comments
555+
{
556+
text: 'Some text here',
557+
user: {
558+
firstName: 'John',
559+
lastName: 'Doe'
560+
},
561+
replies: [
562+
{
563+
text: 'A reply here',
564+
user: {
565+
firstName: 'Joe',
566+
lastName: 'Doe'
567+
}
568+
},
569+
{
570+
text: 'Another reply here',
571+
user: {
572+
firstName: 'Mary',
573+
lastName: 'Doe'
574+
},
575+
replies: [
576+
{
577+
text: 'Yes, this is the reply of the reply!',
578+
user: {
579+
firstName: 'Max',
580+
lastName: 'Doe'
581+
}
582+
}
583+
]
584+
}
585+
]
586+
}
587+
```
588+
589+
Then we just need to set `user` to User model and `replies` to Comment model:
590+
591+
**/models/Comment.js**
592+
```js
593+
class Comment extends Model {
594+
relations () {
595+
return {
596+
// Apply User model to `user` object
597+
user: User,
598+
// Apply Comment model to each object of `replies` array
599+
replies: Comment
600+
}
601+
}
602+
}
603+
```
520604

521605
# Pagination
522606

0 commit comments

Comments
 (0)