Relations
Defining relations
Relations need no extra declarations. A field whose type is another model links the two, and KScript.Data works out the kind of link from the fields on both sides:
<import package="KScript.Data" />
<model name="User">
<field name="name" type="string" />
<field name="posts" type="Post[](by: author)" />
<field name="profile?" type="Profile" />
</model>
<model name="Profile">
<field name="user" type="User" />
<field name="bio" type="string" />
</model>
<model name="Post">
<field name="title" type="string" />
<field name="published" type="bool" default="false" />
<field name="author" type="User" />
<field name="tags" type="Tag[]" />
</model>
<model name="Tag">
<field name="name" type="string" />
<field name="posts" type="Post[]" />
</model>import KScript.Data
model User {
name: string
posts: Post[](by: author)
profile?: Profile
}
model Profile {
user: User
bio: string
}
model Post {
title: string
published: bool = false
author: User
tags: Tag[]
}
model Tag {
name: string
posts: Post[]
}Here is what each kind of field means.
Belongs to. author: User on Post stores an author_id column, a foreign key to users. The model gets an author_id field too.
Has one. profile?: Profile on User, where Profile has user: User, is kept as user_id on profiles. The side that has one is the optional side.
Has many. posts: Post[] on User, where Post has a field that is a User, uses that field's column on posts. When Post has more than one such field (say author and editor), name the one you mean with by:, as in posts: Post[](by: author).
Many to many. tags: Tag[] on Post, where Tag has a list of Posts rather than one, is kept in a pivot table named post_tag, with post_id and tag_id. Name the table yourself with pivot:.
Has many through. comments: Comment[](through: posts) reads the comments of this user's posts, through another relation. It stores nothing of its own.
A relation may also keep only the records one of the other model's scopes keeps: drafts: Post[](by: author, scope: drafts).
On a belongs-to field, on_delete: says what happens when the record it points to is deleted. cascade deletes this record too, and is the default for a required field. set_null empties the field, and is the default for an optional one. restrict refuses the delete with a ForeignKeyViolation error.
Two models that refer to each other may each live in their own file without importing the other. When a field names a model that isn't imported, it's found in the project's models folder (paths.models in kscript.json). This is the one place a model is found without an import, because otherwise the two files would import each other, and circular imports aren't allowed. Scripts and controllers that use a model still import its file. See one type per file.
Reading relations
To read a relation, read it like a field. You get one record (or null) for belongs to and has one, and a list for the others:
<let name="ada" value="User->create(name: 'Ada')" />
<let name="post" value="$ada->posts()->create(title: 'Notes on the engine')" />
<echo value="$post.author.name" />
<echo value="$ada.posts->map(.title)" />$ada = User->create(name: 'Ada')
$post = $ada->posts()->create(title: 'Notes on the engine')
echo $post.author.name
echo $ada.posts->map(.title)When you read a relation on records that came from the same list, it's loaded for the whole list at once. A loop like this one makes one query for all the authors, not one for each post:
<for each="post" in="Post->latest()->get()">
<echo>{$post.title} by {$post.author.name}</echo>
</for>for post in Post->latest()->get() {
echo "{$post.title} by {$post.author.name}"
}Loading relations up front
->with() loads relations together with the records. A dotted name loads a relation's own relations:
<let name="users" value="User->with(profile, posts.tags)->get()" />$users = User->with(profile, posts.tags)->get()If you only want some of the related records, give a function that changes the relation's query:
<let name="users" value="User->with(posts: fn(q) => $q->where(published: true))->get()" />$users = User->with(posts: fn(q) => $q->where(published: true))->get()->load() does the same for a record you already have:
<do>$post->load(author, tags)</do>$post->load(author, tags)A relation that hasn't been loaded is left out of JSON, so a route's response includes only the relations you loaded.
To count related records without reading them, use ->with_count(). Each record gets a posts_count field, counted by the database:
<let name="authors" value="User->with_count(posts)->get()" />$authors = User->with_count(posts)->get()Querying relations
Calling a relation as a method, such as $ada->posts(), gives a query of the related records. You may filter it, count it, or add to it, and everything stays within that user's posts:
<import package="KScript.Data" />
<echo value="$ada->posts()->where(published: false)->count()" />
<do>$ada->posts()->create(title: 'A second post')</do>import KScript.Data
echo $ada->posts()->where(published: false)->count()
$ada->posts()->create(title: 'A second post')->create() on a relation sets the link for you: the new post's author is Ada.
A many-to-many relation is linked through its pivot table. ->attach() links records (or keys, or a list of either), keeping links that are already there. ->detach() unlinks the records you give, or all of them. ->sync() links exactly the records you give and unlinks the rest, and ->toggle() flips each one:
<import package="KScript.Data" />
<let name="maths" value="Tag->create(name: 'maths')" />
<do>$post->tags()->attach($maths)</do>
<do>$post->tags()->sync([$maths])</do>import KScript.Data
$maths = Tag->create(name: 'maths')
$post->tags()->attach($maths)
$post->tags()->sync([$maths])A belongs-to relation is set on the record itself. $post.author = $ben sets author_id, and $post->save() writes it.
Relations in conditions
A condition may read through relations, and the database does the work:
<let name="busy" value="User->where(fn(u) => $u.posts->count() > 10)->get()" />
<let name="tagged" value="Post->where(fn(p) => $p.tags->any(fn(t) => $t.name == 'maths'))->get()" />
<let name="by_ada" value="Post->where(fn(p) => $p.author.name == 'Ada')->get()" />
<let name="no_profile" value="User->where(fn(u) => $u.profile == null)->get()" />$busy = User->where(fn(u) => $u.posts->count() > 10)->get()
$tagged = Post->where(fn(p) => $p.tags->any(fn(t) => $t.name == 'maths'))->get()
$by_ada = Post->where(fn(p) => $p.author.name == 'Ada')->get()
$no_profile = User->where(fn(u) => $u.profile == null)->get()On a list relation, ->count(), ->any(), ->is_empty(), ->all(), ->sum(), ->average(), ->min() and ->max() become SQL, each with an optional lambda on the related record. On a single related record, you may read its fields, compare it with a record, or compare it with null. Comparing with a record also works with the short form:
<let name="mine" value="Post->where(author: $ada)->get()" />$mine = Post->where(author: $ada)->get()Scopes on relations
A scope works on a relation too, and keeps to the relation's records: $ada->posts()->live()->count() counts only Ada's live posts.