“在当前作用域中未找到名为 struct `sea_orm::Select` 的名为 `paginate` 的方法”

问题描述 投票:0回答:1

我在所有实体上为 findAll 使用通用函数。现在我尝试实现分页,但找不到分页方法。

我假设我缺少一些通用参数。

这是我目前的做法:

use sea_orm::{DatabaseConnection, EntityTrait, PaginatorTrait};

use crate::dto::pagination::{Paginated, Pagination};

pub(crate) async fn get_all<T>(
    conn: &DatabaseConnection,
    pagination: Pagination,
) -> Result<Paginated<T::Model>, Error>
where
    T: EntityTrait,
{
    let pages = T::find().paginate(conn, pagination.limit);

    let entities: Vec<T::Model> = pages.fetch_page(pagination.page).await?;

    let paginated = Paginated {
        data: entities,
        page: pagination.page,
        total: pages.num_pages().await?,
        limit: pagination.limit,
    };

    Ok(paginated)
}

这是我实现分页之前的方法:

pub(crate) async fn get_all<T>(conn: &DatabaseConnection) -> Result<Vec<T::Model>, Error>
where
    T: EntityTrait,
{
    let entities = T::find().all(conn).await?;

    Ok(entities)
}

实体是由seaorm生成的,这就是我尝试使用该方法的方式:

generic_repository::get_all::<myEntity::Entity>(&state.conn, pagination).await?;

编译器显示:

error[E0599]: no method named `paginate` found for struct `sea_orm::Select` in the current scope
  --> src\repository\generic_repository.rs:28:27
   |
28 |     let pages = T::find().paginate(conn, pagination.limit);
   |                           ^^^^^^^^ method not found in `Select<T>`

error: aborting due to previous error; 8 warnings emitted

For more information about this error, try `rustc --explain E0599`.
error: could not compile `replaces_my_appname-api` (bin "replaces_my_appname-api") due to 2 previous errors; 8 warnings emitted
Process finished with exit code 101
generics rust pagination findall sea-orm
1个回答
0
投票

您还必须为模型添加一些特征:

use sea_orm::{DatabaseConnection, EntityTrait, PaginatorTrait};

use crate::dto::pagination::{Paginated, Pagination};

pub(crate) async fn get_all<T, M>(
    conn: &DatabaseConnection,
    pagination: Pagination,
) -> Result<Paginated<T::Model>, Error>
where
    T: EntityTrait<Model=M>,
    M: FromQueryResult + Sized + Send + Sync,
{
    let pages = T::find().paginate(conn, pagination.limit);

    let entities: Vec<T::Model> = pages.fetch_page(pagination.page).await?;

    let paginated = Paginated {
        data: entities,
        page: pagination.page,
        total: pages.num_pages().await?,
        limit: pagination.limit,
    };

    Ok(paginated)
}
© www.soinside.com 2019 - 2024. All rights reserved.