問題描述:
使用SeaOrm保存實體到數據庫時不想每次都設置更新時間,所以想通過實現ActiveModelBehavior在保存實體前統一設置更新時間?
impl ActiveModelBehavior for ActiveModel {async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>whereC: ConnectionTrait,{println!("account OrderActiveModelModelBehavior::before_save");let mut active_model = self;// Set updated_at to current Local timeactive_model.updated_at = Set(chrono::Local::now().into());Ok(active_model)}}
運行cargo check報錯:
error[E0195]: lifetime parameters or bounds on method `before_save` do not match the trait declaration
? --> src\models\order_model.rs:12:25
? ?|
12 | ? ? async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
? ?|\u001b[0m ? ? ? ? ? ? ? ? ? ? ? ? ^^^ lifetimes do not match method in trait
?
解決方法:
使用#[async_trait]注解
修改后的代碼:
#[async_trait]
impl ActiveModelBehavior for ActiveModel {async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>whereC: ConnectionTrait,{println!("account OrderActiveModelModelBehavior::before_save");let mut active_model = self;// Set updated_at to current Local timeactive_model.updated_at = Set(chrono::Local::now().into());Ok(active_model)}}
問題原因:
因為使用了異步特征,目前還需要借助第三方crate把我們的代碼轉換成異步特征支持的形式而不用關心腳手架代碼