Skip to main content

Relation

Derive Macro Relation 

Source
#[derive(Relation)]
{
    // Attributes available to this derive:
    #[relation]
    #[table]
    #[column]
}
Expand description

派生宏:自动生成 sz_orm_core::model::ModelExt trait 实现, 填充 relations() 映射,消除手写关系样板代码。

§支持的属性

  • #[relation(has_many = "orders", fk = "user_id", pk = "id")]
  • #[relation(belongs_to = "users", fk = "user_id", pk = "id")]
  • #[relation(has_one = "profile", fk = "user_id", pk = "id")]
  • #[relation(belongs_to_many = "roles", junction = "user_roles", fk = "user_id", other_key = "role_id", target = "roles", target_pk = "id")]
  • #[relation(morph_many = "comments", morph_type = "commentable_type", morph_id = "commentable_id", morph_type_value = "Post")]
  • #[relation(morph_to, morph_type = "commentable_type", morph_id = "commentable_id")]

§示例

use sz_orm_macros::{Entity, Relation};

#[derive(Entity, Relation)]
#[table(name = "users")]
struct User {
    #[column(primary_key)]
    id: i64,
}

// 自动生成:
// impl ModelExt for User {
//     fn relations() -> HashMap<&str, Relation> {
//         // 包含 #[relation] 定义的关系
//     }
// }