pub trait HasQuery<DB: Backend>: SelectableHelper<DB, SelectExpression: QueryId + AppearsOnTable<<Self::BaseQuery as AcceptedQueries>::From> + ValidGrouping<<Self::BaseQuery as AcceptedQueries>::GroupBy>> {
type BaseQuery: AcceptedQueries + SelectDsl<AsSelect<Self, DB>, Output: Query>;
// Provided method
fn query() -> Select<Self::BaseQuery, AsSelect<Self, DB>> { ... }
}
Expand description
Trait indicating that a base query can be constructed for this type
Types which implement HasQuery
have a default query for loading
the relevant data from the database associated with this type.
Consumers of this trait should use the query()
associated function
to construct a query including a matching select clause for their type
This trait can be derived
It’s important to note that for Diesel mappings between the database and rust types always happen on query and not on table level. This enables you to write several queries related to the same table, while a single query could be related to zero or multiple tables.
§Example
§With derive
// it's important to have the right table in scope
use schema::users;
#[derive(HasQuery, PartialEq, Debug)]
struct User {
id: i32,
name: String,
}
// equivalent to `users::table.select(User::as_select()).first(connection)?;
let first_user = User::query().first(connection)?;
let expected = User { id: 1, name: "Sean".into() };
assert_eq!(expected, first_user);
§Manual implementation
// it's important to have the right table in scope
use schema::users;
#[derive(Selectable, Queryable, PartialEq, Debug)]
struct User {
id: i32,
name: String,
}
impl<DB: diesel::backend::Backend> diesel::HasQuery<DB> for User {
type BaseQuery = <users::table as diesel::query_builder::AsQuery>::Query;
// internal not stable method
fn base_query() -> Self::BaseQuery {
use diesel::query_builder::AsQuery;
users::table.as_query()
}
}
// equivalent to `users::table.select(User::as_select()).first(connection)?;
let first_user = User::query().first(connection)?;
let expected = User { id: 1, name: "Sean".into() };
assert_eq!(expected, first_user);
Required Associated Types§
Provided Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.