我正在尝试将柴油用于一个项目,并且我想要一种“可过滤”类型。这个想法是你可以去 /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/