@@ -40,7 +40,7 @@ export default class Model extends BaseModel {
40
40
41
41
## Creating the Domain Models
42
42
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.
44
44
45
45
Each model must implement:
46
46
- ` resource ` - The resource route of the model.
@@ -59,6 +59,30 @@ export default class User extends Model {
59
59
60
60
This ** User** model will make request to ` /users ` route as defined in ` resource ` .
61
61
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
+
62
86
## Changing the Primary Key
63
87
64
88
<alert type =" info " >By default, the ` primaryKey ` is set to ` id ` .</alert >
@@ -132,6 +156,35 @@ export default class Post extends Model {
132
156
Now we can easily access an instance of the ** User** model containing the eager loaded data
133
157
using the specified key: ` post.user `
134
158
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
+
135
188
### Lazy Loading Relationships
136
189
137
190
See the [ API reference] ( /api/model-options#hasmany )
@@ -154,6 +207,17 @@ export default class User extends Model {
154
207
posts() {
155
208
return this.hasMany(Post)
156
209
}
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
+ }
157
221
}
158
222
```
159
223
0 commit comments