[英]Rust diesel conditionally filter a query
I am trying to use diesel for a project and I would like to have a "filterable" type.我正在尝试将柴油用于一个项目,并且我想要一种“可过滤”类型。 The idea is that you can go to
/api/foo?id=10&bar=11
and it would return a struct Foo
:这个想法是你可以 go 到
/api/foo?id=10&bar=11
并且它会返回一个 struct Foo
:
struct Foo {
id: Option<i64>,
bar: Option<i64>,
name: Option<String>,
}
Such as:如:
Foo {
id: Some(10),
bar: Some(11),
name: None,
}
I've been scouring the internet for a way to filter by the fields that exist, but I am unable to find a solution that works.我一直在互联网上寻找一种按现有字段进行过滤的方法,但我找不到有效的解决方案。 I was initially using the mysql driver and constructing sql queries with proc macros, but diesel is a lot nicer to work with and I was wondering if there was a way to get the same behaviour I had with the mysql driver with diesel.
我最初使用mysql 驱动程序并使用 proc 宏构造 sql 查询,但是使用柴油机要好得多,我想知道是否有办法获得与 Z81C3B080DAD537B57E10E0978 柴油机相同的行为。
You can use the into_boxed
method, which:您可以使用
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.