You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SeaORM调用.all()报错:Data<DatabaseConnection>未实现ConnectionTrait

Actix Web + SeaORM:web::Data无法用于查询的解决办法

问题

在Actix Web项目中,尝试将web::Data<DatabaseConnection>传入SeaORM的.all()方法执行查询时,触发编译错误,提示该类型未实现ConnectionTrait trait,而DatabaseConnection和DatabaseTransaction已实现该trait。

报错信息

error[E0277]: the trait bound `Data<DatabaseConnection>: ConnectionTrait` is not satisfied
   --> src/main.rs:27:34
    |
27  |     let q = Articles::find().all(&data).await;
    |                              --- ^^^^^ the trait `ConnectionTrait` is not implemented for `Data<DatabaseConnection>`
    |                              |
    |                              required by a bound introduced by this call
    |
= help: the following other types implement trait `ConnectionTrait`:
              DatabaseConnection
              DatabaseTransaction
note: required by a bound in `sea_orm::executor::select::<impl sea_orm::Select<E>>::all`
   --> /Users//.cargo/registry/src/git/sea-orm-0.10.6/src/executor/select.rs:267:12
    |
267 |         C: ConnectionTrait,
    |            ^^^^^^^^^^^^^^^ required by this bound in `sea_orm::executor::select::<impl sea_orm::Select<E>>::all`

代码示例(main.rs)

async fn test(data: web::Data<DatabaseConnection>) -> HttpResponse {
    dbg!(&data);

    let q = Articles::find().all(&data).await;

    HttpResponse::Ok().json("test")
}

async fn get_connection() -> DatabaseConnection {
    Database::connect("postgres://...")
        .await
        .expect("Failed to connect to database!")
}

#[actix_web::main]
async fn main() -> Result<()> {
    let db = get_connection().await;

    HttpServer::new(move || {
        App::new()
            .service(web::resource("/").route(web::get().to(test)))
            .app_data(web::Data::new(db.clone()))
    })
    .bind(("127.0.0.1", 8888))?
    .run()
    .await?;

    Ok(())
}

解决方法

问题出在web::Data<DatabaseConnection>是Actix用于共享数据的包裹类型,它本身并没有实现SeaORM的ConnectionTrait,但内部包裹的DatabaseConnection是符合要求的。只需要从Data中取出内部实例的引用即可,有两种常用方式:

方式1:使用解引用操作符

修改查询代码,通过&*data获取内部DatabaseConnection的引用:

let q = Articles::find().all(&*data).await;

方式2:使用as_ref()方法

调用Data提供的as_ref()方法直接获取内部引用:

let q = Articles::find().all(data.as_ref()).await;

原因解释

web::Data<T>本质是一个线程安全的智能指针,实现了Deref<Target = T> trait,所以可以通过*data解引用得到内部的T实例,再取引用就符合ConnectionTrait的要求了。as_ref()方法则是更直观的API,专门用于获取内部值的引用。

内容的提问来源于stack exchange,提问作者Nkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:01:33