Skip to content

Commit 25822c8

Browse files
committed
update
1 parent 16d96b1 commit 25822c8

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

versioned_docs/version-3.x/orm/computed-fields.md

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,33 @@ model User {
3030
Then, when creating a `ZenStackClient`, provide the implementation of the field using the Kysely query builder.
3131

3232
```ts
33-
import { ZenStackClient } from '@zenstackhq/runtime';
34-
3533
const db = new ZenStackClient(schema, {
3634
...
3735
computedFields: {
3836
User: {
3937
postCount: (eb) =>
4038
eb.selectFrom('Post')
41-
.whereRef('Post.authorId', '=', 'User.id')
39+
.whereRef('Post.authorId', '=', 'id')
40+
.select(({fn}) => fn.countAll<number>().as('count')),
41+
},
42+
},
43+
});
44+
```
45+
46+
The computed field callback is also passed with a second `context` argument containing other useful information related to the current query. For example, you can use the `currentModel` property to refer to the containing model and use it to qualify field names in case of conflicts.
47+
48+
```ts
49+
import { sql } from 'kysely';
50+
51+
const db = new ZenStackClient(schema, {
52+
...
53+
computedFields: {
54+
User: {
55+
postCount: (eb, { currentModel }) =>
56+
eb.selectFrom('Post')
57+
// the `currentModel` context property gives you a name that you can
58+
// use to address the containing model (here `User`) at runtime
59+
.whereRef('Post.authorId', '=', sql.ref(currentModel, 'id'))
4260
.select(({fn}) => fn.countAll<number>().as('count')),
4361
},
4462
},

0 commit comments

Comments
 (0)