sarala
Version:
Javascript library to communicate with RESTful API built following JSON API specification. inspired by Laravel’s Eloquent.
65 lines (45 loc) • 1.58 kB
Markdown
---
sidebarDepth: 0
---
You may implement `relationships` method on the model to specify its relationships. Sarala expects `relationships` method to return a json object, mapped key to the **relationship name** name and value to the **related model instance**.
Each key value pair represents a relationship to the model, regardless whether it is one to many, many to many or etc.
```javascript
import Model from './BaseModel'
import Comment from './Comment'
import Tag from './Tag'
import User from './User'
export default class Post extends Model {
// ..
relationships () {
return {
author: new User(),
comments: new Comment(),
tags: new Tag()
}
}
// ..
}
```
```javascript
import Post from 'app/models/Post'
const post = new Post()
let thePost = await post.with(['author', 'tags']).find(8)
```
Relationships you have specified can be retrieve as instance properties.
```
NOTE: relationship property returns a json object: { data, links, meta }
```
```javascript
let theAuthor = {}
{ data: theAuthor } = thePost.author
console.log(theAuthor.name) // John Doe
```
```javascript
let myTags = []
{ data: myTags } = thePost.tags
console.log(myTags.length) // 3
```