wip refactoring
This commit is contained in:
@@ -11,6 +11,30 @@ pub struct Model {
|
||||
pub r#type: String,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// Get an entity that has the same content and returns its ID or creates a new entity and
|
||||
/// returns its ID
|
||||
pub async fn get_or_create(content: String, db: &DatabaseConnection) -> Result<i32, DbErr> {
|
||||
let content_db = Entity::find()
|
||||
.filter(Column::Content.eq(&content))
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
let content_db = match content_db {
|
||||
Some(x) => x,
|
||||
None => {
|
||||
let activeModel = ActiveModel {
|
||||
id: sea_orm::ActiveValue::NotSet,
|
||||
content: sea_orm::ActiveValue::Set(content),
|
||||
r#type: sea_orm::ActiveValue::Set("".to_string()),
|
||||
};
|
||||
activeModel.insert(db).await.unwrap()
|
||||
}
|
||||
};
|
||||
Ok(content_db.id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::messages::Entity")]
|
||||
|
||||
@@ -30,6 +30,28 @@ impl Model {
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
pub async fn get_or_create(
|
||||
id: i64,
|
||||
name: String,
|
||||
db: &DatabaseConnection,
|
||||
) -> Result<i32, DbErr> {
|
||||
let member = Entity::find()
|
||||
.filter(Column::IdDiscord.eq(id))
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
match member {
|
||||
Some(x) => Ok(x.id),
|
||||
None => {
|
||||
let activeModel = ActiveModel {
|
||||
id: sea_orm::ActiveValue::NotSet,
|
||||
id_discord: sea_orm::ActiveValue::Set(id),
|
||||
name: sea_orm::ActiveValue::Set(name),
|
||||
};
|
||||
Ok(activeModel.insert(db).await?.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
|
||||
Reference in New Issue
Block a user