使用异步特征引发的错误error[E0195]: lifetime parameters or bounds on method `before_save`

问题描述:

使用SeaOrm保存实体到数据库时不想每次都设置更新时间,所以想通过实现ActiveModelBehavior在保存实体前统一设置更新时间 

impl ActiveModelBehavior for ActiveModel {


    async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        println!("account OrderActiveModelModelBehavior::before_save");
        let mut active_model = self;
        // Set updated_at to current Local time
        active_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>
    where
        C: ConnectionTrait,
    {
        println!("account OrderActiveModelModelBehavior::before_save");
        let mut active_model = self;
        // Set updated_at to current Local time
        active_model.updated_at = Set(chrono::Local::now().into());
        Ok(active_model)
    }

}


问题原因:

因为使用了异步特征,目前还需要借助第三方crate把我们的代码转换成异步特征支持的形式而不用关心脚手架代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CoderFusionZhu

不要打赏太多哦!我喝速溶就行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值