db/models/
announcements.rs

1
2use chrono::{DateTime, Utc};
3use sea_orm::ActiveValue::Set;
4use sea_orm::entity::prelude::*;
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)]
8#[sea_orm(table_name = "announcements")]
9pub struct Model {
10    #[sea_orm(primary_key)]
11    pub id: i64,
12
13    pub module_id: i64,
14    pub user_id: i64,
15
16    pub title: String,
17    pub body: String,
18    pub pinned: bool,
19
20    pub created_at: DateTime<Utc>,
21    pub updated_at: DateTime<Utc>,
22}
23
24#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
25pub enum Relation {
26    #[sea_orm(
27        belongs_to = "super::module::Entity",
28        from = "Column::ModuleId",
29        to = "super::module::Column::Id",
30        on_delete = "Cascade"
31    )]
32    Module,
33
34    #[sea_orm(
35        belongs_to = "super::user::Entity",
36        from = "Column::UserId",
37        to = "super::user::Column::Id",
38        on_delete = "Cascade"
39    )]
40    User,
41}
42
43impl Related<super::module::Entity> for Entity {
44    fn to() -> RelationDef {
45        Relation::Module.def()
46    }
47}
48
49impl Related<super::user::Entity> for Entity {
50    fn to() -> RelationDef {
51        Relation::User.def()
52    }
53}
54
55impl ActiveModelBehavior for ActiveModel {}
56
57impl Model {
58    pub async fn create(
59        db: &DbConn,
60        module_id: i64,
61        user_id: i64,
62        title: &str,
63        body: &str,
64        pinned: bool,
65    ) -> Result<Model, DbErr> {
66        let now = Utc::now();
67        let announcement = ActiveModel {
68            module_id: Set(module_id),
69            user_id: Set(user_id),
70            title: Set(title.to_owned()),
71            body: Set(body.to_owned()),
72            pinned: Set(pinned),
73            created_at: Set(now),
74            updated_at: Set(now),
75            ..Default::default()
76        };
77
78        announcement.insert(db).await
79    }
80
81    pub async fn delete(db: &DbConn, id: i64) -> Result<(), DbErr> {
82        Entity::delete_by_id(id).exec(db).await?;
83        Ok(())
84    }
85
86    pub async fn update(
87        db: &DbConn,
88        id: i64,
89        title: &str,
90        body: &str,
91        pinned: bool,
92    ) -> Result<Model, DbErr> {
93        let mut announcement = ActiveModel {
94            id: Set(id),
95            updated_at: Set(Utc::now()),
96            ..Default::default()
97        };
98
99        if !title.is_empty() {
100            announcement.title = Set(title.to_owned());
101        }
102        if !body.is_empty() {
103            announcement.body = Set(body.to_owned());
104        }
105        announcement.pinned = Set(pinned);
106
107        announcement.update(db).await
108    }
109}