小编unk*_*ean的帖子

使用动态数量的.and()创建Diesel.rs查询

在玩Diesel时,我遇到了写一个函数的问题,该函数将Strings 的向量作为输入并执行以下操作:

  1. 将所有Strings 组合到一个大型查询中
  2. 在上运行查询 Connection
  3. 处理结果
  4. 回来一个 Vec

如果我一步构建查询,它可以正常工作:

fn get_books(authors: Vec<String>, connection: SqliteConnection) {
    use schema::ebook::dsl::*;

    let inner = author
        .like(format!("%{}%", authors[0]))
        .and(author.like(format!("%{}%", authors[1])))
        .and(author.like(format!("%{}%", authors[2])));

    ebook
        .filter(inner)
        .load::<Ebook>(&connection)
        .expect("Error loading ebook");
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试以更多步骤生成查询(为了使用输入向量的可变长度需要),我无法编译它:

fn get_books(authors: Vec<String>, connection: SqliteConnection) {
    use schema::ebook::dsl::*;

    let mut inner = author
        .like(format!("%{}%", authors[0]))
        .and(author.like(format!("%{}%", authors[1]))); // <1>

    inner = inner.and(author.like(format!("%{}%", authors[2]))); // <2>

    ebook
        .filter(inner)
        .load::<Ebook>(&connection)
        .expect("Error loading ebook");
}
Run Code Online (Sandbox Code Playgroud)

这会生成以下错误:

inner = inner.and(author.like(format!("%{}%",authors[2])));
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `diesel::expression::operators::Like`, …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

6
推荐指数
1
解决办法
1193
查看次数

标签 统计

rust ×1

rust-diesel ×1