관계
관계 정의하기
관계를 위해 별도의 선언은 필요하지 않아요. 다른 모델을 타입으로 가진 필드가 두 모델을 연결하며, KScript.Data가 양쪽 필드를 보고 연결의 종류를 알아내요:
<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[]
}각 종류의 필드가 무엇을 의미하는지 살펴볼게요.
소속 관계(Belongs to). Post의 author: User은 author_id 열을 저장해요. 이는 users를 가리키는 외래 키예요. 이 모델에는 author_id 필드도 생겨요.
일대일 관계(Has one). Profile에 user: User가 있는 경우, User의 profile?: Profile은 profiles의 user_id로 저장돼요. 일대일을 가지는 쪽이 선택적인 쪽이에요.
일대다 관계(Has many). Post에 User 타입의 필드가 있는 경우, User의 posts: Post[]은 posts에 있는 그 필드의 열을 사용해요. Post에 그런 필드가 둘 이상 있다면(예: author와 editor), by:로 어느 것인지 지정하세요. 예를 들어 posts: Post[](by: author)처럼 쓰면 돼요.
다대다 관계(Many to many). Tag에 Post 하나가 아니라 Post 목록이 있는 경우, Post의 tags: Tag[]은 post_tag라는 이름의 연결 테이블에 저장되며, 이 테이블에는 post_id와 tag_id가 들어가요. 테이블 이름은 pivot:로 직접 정할 수 있어요.
간접 일대다 관계(Has many through). comments: Comment[](through: posts)은 다른 관계를 거쳐 이 사용자 게시물의 댓글을 읽어요. 자체적으로 저장하는 것은 없어요.
관계는 상대 모델의 스코프가 남기는 레코드만 가져올 수도 있어요: drafts: Post[](by: author, scope: drafts).
소속 관계 필드에서 on_delete:은 가리키는 레코드가 삭제될 때 어떻게 할지를 정해요. cascade는 이 레코드도 함께 삭제하며, 필수 필드의 기본값이에요. set_null는 필드를 비우며, 선택 필드의 기본값이에요. restrict는 ForeignKeyViolation 오류를 내면서 삭제를 막아요.
서로를 참조하는 두 모델은 상대를 import하지 않고 각자 파일에 둘 수 있어요. 필드가 import되지 않은 모델의 이름을 가리키면, 프로젝트의 모델 폴더(kscript.json 안의 paths.models)에서 찾아요. 두 파일이 서로를 import하게 되어 순환 import가 생기는 것을 피하기 위해, import 없이 모델을 찾는 것은 이 경우에만 해당해요. 다만 모델을 사용하는 스크립트와 컨트롤러는 여전히 해당 파일을 import해야 해요. 파일당 타입 하나를 참고하세요.
관계 읽기
관계를 읽으려면 필드처럼 읽으면 돼요. 소속 관계와 일대일 관계는 레코드 하나(또는 null)를, 나머지는 목록을 받아요:
<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)같은 목록에서 가져온 레코드들의 관계를 읽으면, 그 관계는 전체 목록에 대해 한 번에 로드돼요. 아래 반복문은 게시물마다 쿼리하지 않고 모든 작성자를 한 번의 쿼리로 가져와요:
<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}"
}관계를 미리 로드하기
->with()은 레코드와 함께 관계를 로드해요. 점으로 구분한 이름은 관계의 관계까지 로드해요:
<let name="users" value="User->with(profile, posts.tags)->get()" />$users = User->with(profile, posts.tags)->get()관련 레코드 일부만 필요하다면, 관계의 쿼리를 바꾸는 함수를 전달하세요:
<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()은 이미 가지고 있는 레코드에 대해 같은 일을 해요:
<do>$post->load(author, tags)</do>$post->load(author, tags)로드되지 않은 관계는 JSON에서 빠지므로, 라우트의 응답에는 로드한 관계만 포함돼요.
관련 레코드를 읽지 않고 개수만 세려면 ->with_count()을 사용하세요. 각 레코드에는 데이터베이스가 센 개수를 담은 posts_count 필드가 생겨요:
<let name="authors" value="User->with_count(posts)->get()" />$authors = User->with_count(posts)->get()관계 쿼리하기
$ada->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()을 호출하면 연결이 자동으로 설정돼요. 새 게시물의 작성자는 Ada가 돼요.
다대다 관계는 연결 테이블을 통해 연결돼요. ->attach()은 레코드(또는 키, 또는 둘 중 하나의 목록)를 연결하며, 이미 있는 연결은 그대로 둬요. ->detach()는 지정한 레코드의 연결을 끊거나, 전부 끊어요. ->sync()는 지정한 레코드만 정확히 연결하고 나머지는 끊으며, ->toggle()는 각 레코드의 연결 상태를 뒤집어요:
<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])소속 관계는 레코드 자체에서 설정해요. $post.author = $ben은 author_id를 설정하고, $post->save()는 그것을 저장해요.
조건에서 관계 사용하기
조건은 관계를 거쳐 읽을 수 있으며, 실제 작업은 데이터베이스가 해요:
<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()목록 관계에서는 ->count(), ->any(), ->is_empty(), ->all(), ->sum(), ->average(), ->min(), ->max()이 각각 SQL로 바뀌며, 각각 관련 레코드에 대한 선택적 람다를 받을 수 있어요. 관련 레코드 하나에 대해서는 그 필드를 읽거나, 레코드와 비교하거나, null와 비교할 수 있어요. 레코드와의 비교는 축약 형태에서도 동작해요:
<let name="mine" value="Post->where(author: $ada)->get()" />$mine = Post->where(author: $ada)->get()관계에 대한 스코프
스코프는 관계에서도 동작하며, 해당 관계의 레코드 안에서만 적용돼요: $ada->posts()->live()->count()은 Ada의 게시물 중 삭제되지 않은 것만 세요.