rust 柴油有条件地过滤一个查询

标签 rust backend rust-diesel

我正在尝试将柴油用于一个项目,并且我想要一种“可过滤”类型。这个想法是你可以去 /api/foo?id=10&bar=11 ,它会返回一个 struct Foo :

struct Foo {
    id: Option<i64>,
    bar: Option<i64>,
    name: Option<String>,
}
如:
Foo {
   id: Some(10),
   bar: Some(11),
   name: None,
}
我一直在互联网上寻找一种按现有字段过滤的方法,但我找不到有效的解决方案。我最初使用 mysql driver 并使用 proc 宏构建 sql 查询,但使用柴油要好得多,我想知道是否有办法获得与使用柴油的 mysql 驱动程序相同的行为。

最佳答案

您可以使用 into_boxed 方法,该方法:

Boxes the pieces of a query into a single type. This is useful for cases where you want to conditionally modify a query, but need the type to remain the same. A boxed query will incur a minor performance penalty, as the query builder can no longer be inlined by the compiler. For most applications this cost will be minimal.


use crate::schema::foo;

let mut query = foo::table.into_boxed();

if let Some(id) = foo.id {
    query = query.filter(foo::id.eq(id));
}

if let Some(bar) = foo.bar {
    query = query.filter(foo::bar.eq(bar));
}

if let Some(name) = foo.name {
    query = query.filter(foo::name.eq(name));
}

let results = query
    .load::<Foo>(&conn)
    .expect("error loading foo");

关于 rust 柴油有条件地过滤一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65039754/

相关文章:

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

arrays - 在 Rust 中传递数组的数组(或切片的切片)

rust - 需要类型注解——为什么关联类型被区别对待?

javascript - 您可以使用 Django 框架将 Python 用于前端和后端吗?

rust - 如何使用 Rocket 中的 Tera 模板在 HTML 中显示使用 Diesel 检索的值?

postgresql - 使用 Diesel 执行插入或更新

rust - 将可变 Arc 引用传递给 hyper service_fn 处理程序

rust - 如何按字符串字段对结构的 Vec 进行排序?

node.js - 使用 MongoDB Stitch 作为 Xamarin 应用程序的后端

database - 揭露假号码/防止假注册/假短信