#[derive(Associations)]
{
// Attributes available to this derive:
#[diesel]
#[belongs_to]
#[column_name]
#[table_name]
}
Expand description
Implement required traits for the associations API
This derive implements support for Diesel’s associations api. Check the
module level documentation of the diesel::associations
module for details.
This derive generates the following impls:
impl BelongsTo<Parent> for YourType
impl BelongsTo<&'a Parent> for YourType
§Attributes
§Required container attributes
#[diesel(belongs_to(User))]
, to specify a child-to-parent relationship between the current type and the specified parent type (User
). If this attribute is given multiple times, multiple relationships are generated.#[diesel(belongs_to(User, foreign_key = mykey))]
variant allows us to specify the name of the foreign key. If the foreign key is not specified explicitly, the remote lower case type name with appended_id
is used as a foreign key name. (user_id
in this example case)
§Optional container attributes
#[diesel(table_name = path::to::table)]
specifies a path to the table this type belongs to. The path is relative to the current module. If this attribute is not used, the type name converted tosnake_case
with an addeds
is used as table name.
§Optional field attributes
#[diesel(column_name = some_column_name)]
, overrides the column the current field maps tosome_column_name
. By default, the field name is used as a column name.
§Expanded Code
Expanded Code
§Input
ⓘ
#[derive(Associations)]
#[diesel(belongs_to(User))]
struct Post {
id: i32,
title: String,
user_id: i32,
}
§Expanded Code
Expanded code might use diesel internal API's and is only shown for educational purpose
The macro expands the input to the following Rust code:
ⓘ
const _: () = {
use diesel;
impl<__FK> diesel::associations::BelongsTo<User> for Post
where
__FK: std::hash::Hash + std::cmp::Eq,
for<'__a> &'__a i32: std::convert::Into<::std::option::Option<&'__a __FK>>,
for<'__a> &'__a User: diesel::associations::Identifiable<Id = &'__a __FK>,
{
type ForeignKey = __FK;
type ForeignKeyColumn = posts::user_id;
fn foreign_key(&self) -> std::option::Option<&Self::ForeignKey> {
std::convert::Into::into(&self.user_id)
}
fn foreign_key_column() -> Self::ForeignKeyColumn {
posts::user_id
}
}
impl<__FK> diesel::associations::BelongsTo<&'_ User> for Post
where
__FK: std::hash::Hash + std::cmp::Eq,
for<'__a> &'__a i32: std::convert::Into<::std::option::Option<&'__a __FK>>,
for<'__a> &'__a User: diesel::associations::Identifiable<Id = &'__a __FK>,
{
type ForeignKey = __FK;
type ForeignKeyColumn = posts::user_id;
fn foreign_key(&self) -> std::option::Option<&Self::ForeignKey> {
std::convert::Into::into(&self.user_id)
}
fn foreign_key_column() -> Self::ForeignKeyColumn {
posts::user_id
}
}
};