[−][src]Macro df_st_db::group_by
Creates a match condition on group_by
used for
counting the items with a particular value in the field that is grouped.
Parameters:
group_by_opt
:Option<String>
, variable used group items, ifNone
it will calculate total.query
: First part of the Diesel query. (stored in variable)conn
:&DbConnection
, connection to database.key => {value: type}
: (first pair will be used as default)key
:&str
, name of the field that matches thegroup_by_opt
.value
: Diesel column, the column that matches the key.type
: They type of the value that is stored in the column. Return: The list of result of the database query stored inItemCount
objects. Example use:
ⓘThis example is not tested
group_by!{ group_by_opt, query, conn,
Example generated code output:
ⓘThis example is not tested
let count_star = diesel::dsl::sql::<diesel::sql_types::BigInt>("count(*)"); if let Some(group_by) = group_by_opt { match group_by.as_ref() { "civ_id" => { let query = sites.select((count_star, civ_id)); let query = query.group_by(civ_id); let result = query.load::<(i64, Option<i32>)>(conn)?; let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{ ItemCount{ count: count as u32, value: serde_json::json!(value), } }).collect(); return Ok(result); } _ => { let query = sites.select((count_star, type_)); let query = query.group_by(type_); let result = query.load::<(i64, Option<String>)>(conn)?; let result: Vec<ItemCount> = result.into_iter().map(|(count,value)|{ ItemCount{ count: count as u32, value: serde_json::json!(value), } }).collect(); return Ok(result); } } } let query = sites.select(count_star); let result = query.load::<i64>(conn)?; let result: Vec<ItemCount> = result.into_iter().map(|count|{ ItemCount{ count: count as u32, value: serde_json::json!("total"), } }).collect();