问题描述:
使用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把我们的代码转换成异步特征支持的形式而不用关心脚手架代码