Querying a Diesel table with dynamic parameters

笑着哭i 提交于 2020-04-13 01:04:20

问题


I was starting to look into using Diesel for querying a database. I have a table that looks something like the struct below (this is just a toy project to help me understand how Diesel works).

#[derive(Queryable, Insertable)]
#[table_name="posts"]
struct Post {
    id: String,
    title: String,
    body: String,
    published: bool
}

Doing queries that are fully determined at compile time is easy enough, for example

posts.select(id, title).order(title.desc());

What is not clear to me is how to build a query depending on some runtime parameters, without having to fall back to SQL. For example JSONAPI allows for dynamically selecting fields and sorting them based on query parameters. How would I do this in Diesel?


回答1:


Using a boxed trait:

let mut q = dsl::constants.into_boxed();

if let Some(sid) = msg.0 {
    q = q.filter(dsl::id.eq(sid));
}

let items = q
    .order(dsl::id)
    .load::<Constant>(conn)
    .expect("Can't load Constant");

Ok(items)


来源:https://stackoverflow.com/questions/42557528/querying-a-diesel-table-with-dynamic-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!