Rust diesel 有条件地过滤查询
Rust diesel conditionally filter a query
我正尝试在一个项目中使用柴油,我想要一个“可过滤”的类型。这个想法是你可以去 /api/foo?id=10&bar=11
它会 return 一个结构 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 driver 柴油。
您可以使用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");
我正尝试在一个项目中使用柴油,我想要一个“可过滤”的类型。这个想法是你可以去 /api/foo?id=10&bar=11
它会 return 一个结构 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 driver 柴油。
您可以使用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");