toasty_core/schema/app/relation/belongs_to.rs
1use crate::{
2 schema::app::{FieldId, FieldTy, ForeignKey, Model, ModelId, Schema},
3 stmt,
4};
5
6/// The owning side of a relationship. Stores the foreign key that references
7/// another model's primary key.
8///
9/// A `BelongsTo` field does not store data in its own column; instead, its
10/// [`ForeignKey`] contains one or more primitive fields on the same model
11/// whose values match the target model's primary key.
12///
13/// # Examples
14///
15/// ```ignore
16/// // Given a `Comment` model that belongs to a `Post`:
17/// let belongs_to: &BelongsTo = comment_field.ty.as_belongs_to_unwrap();
18/// let post_model = belongs_to.target(&schema);
19/// ```
20#[derive(Debug, Clone)]
21pub struct BelongsTo {
22 /// The [`ModelId`] of the referenced (target) model.
23 pub target: ModelId,
24
25 /// The expression type this field evaluates to from the application's
26 /// perspective.
27 pub expr_ty: stmt::Type,
28
29 /// The inverse [`HasMany`](super::HasMany) or [`HasOne`](super::HasOne)
30 /// field on the target model, if one exists.
31 pub pair: Option<FieldId>,
32
33 /// The foreign key mapping source fields to the target's primary key
34 /// fields.
35 pub foreign_key: ForeignKey,
36}
37
38impl BelongsTo {
39 /// Resolves the target [`Model`] from the given schema.
40 pub fn target<'a>(&self, schema: &'a Schema) -> &'a Model {
41 schema.model(self.target)
42 }
43}
44
45impl From<BelongsTo> for FieldTy {
46 fn from(value: BelongsTo) -> Self {
47 Self::BelongsTo(value)
48 }
49}