@@ -40,7 +40,7 @@ export default class Model extends BaseModel {
4040
4141## Creating the Domain Models
4242
43- Now let's create our domain models that extends the base model. We can create as many models as you like.
43+ Now let's create our domain models that extends the base model. We can create as many models as we like.
4444
4545Each model must implement:
4646- ` resource ` - The resource route of the model.
@@ -59,6 +59,30 @@ export default class User extends Model {
5959
6060This ** User** model will make request to ` /users ` route as defined in ` resource ` .
6161
62+ We can also add extra methods and computed properties:
63+
64+ ``` js{}[~/models/User.js]
65+ import Model from './Model'
66+
67+ export default class User extends Model {
68+ // Set the resource route of the model
69+ resource() {
70+ return 'users'
71+ }
72+
73+ // Computed properties are reactive -> user.fullName
74+ // Make sure to use "get" prefix
75+ get fullName () {
76+ return `${this.firstname} ${this.lastname}`
77+ }
78+
79+ // Method -> user.makeBirthday()
80+ makeBirthday() {
81+ return this.age += 1
82+ }
83+ }
84+ ```
85+
6286## Changing the Primary Key
6387
6488<alert type =" info " >By default, the ` primaryKey ` is set to ` id ` .</alert >
@@ -132,6 +156,35 @@ export default class Post extends Model {
132156Now we can easily access an instance of the ** User** model containing the eager loaded data
133157using the specified key: ` post.user `
134158
159+ The ` relations ` method also support nested keys, by dot notation:
160+
161+ ``` js{}[~/models/Post.js]
162+ import Model from './Model'
163+ import User from './User'
164+ import Comment from './Comment'
165+
166+ export default class Post extends Model {
167+ // Set the resource route of the model
168+ resource() {
169+ return 'posts'
170+ }
171+
172+ // Define the primary key of the model
173+ primaryKey() {
174+ return 'slug'
175+ }
176+
177+ // Apply model instances to eager loaded relationships
178+ relations() {
179+ return {
180+ 'relationships.user': User,
181+ 'relationships.comments': Comment
182+ }
183+ }
184+ ```
185+
186+ Then we can access using the specified key: ` post.relationships.user `
187+
135188### Lazy Loading Relationships
136189
137190See the [ API reference] ( /api/model-options#hasmany )
@@ -154,6 +207,17 @@ export default class User extends Model {
154207 posts() {
155208 return this.hasMany(Post)
156209 }
210+
211+ // Computed properties are reactive -> user.fullName
212+ // Make sure to use "get" prefix
213+ get fullName () {
214+ return `${this.firstname} ${this.lastname}`
215+ }
216+
217+ // Method -> user.makeBirthday()
218+ makeBirthday() {
219+ return this.age += 1
220+ }
157221}
158222```
159223
0 commit comments