出现以下错误:
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(())
}
您的错误显示“特征
ConnectionTrait
未针对Data<DatabaseConnection>
实现”
这意味着 web::Data 没有实现 ConnectionTrait,因此您无法调用 Articles.find().all(&data),因为数据的类型为 web::Data
您首先需要解开数据
async fn test(data: web::Data<DatabaseConnection>) -> HttpResponse {
dbg!(&data);
let conn = data.unwrap();
let q = Articles::find().all(&conn).await;
HttpResponse::Ok().json("test")
}