Module diesel::associations [] [src]

Traits related to relationships between multiple tables.

Note: This feature is under active development, and we are seeking feedback on the APIs that have been released. Please feel free to open issues, or join our chat to provide feedback.

Note: The derives in this guide are provided by diesel_codegen. Make sure you have #[macro_use] extern crate diesel_codegen; at the root of your crate.

Associations in Diesel are bidirectional, but primarily focus on the child-to-parent relationship. You can declare an association between two records with #[belongs_to].

// You need to have the table definitions from `infer_schema!` or `table!` in scope to
// derive Identifiable.
use schema::{posts, users};

#[derive(Identifiable, Queryable)]
pub struct User {
    id: i32,
    name: String,

#[derive(Identifiable, Queryable, Associations)]
pub struct Post {
    id: i32,
    user_id: i32,
    title: String,

Note that in addition to the #[belongs_to] annotation, we also need to #[derive(Associations)]

#[belongs_to] is given the name of the struct that represents the parent. Both types must implement the Identifiable trait. The struct or table referenced in your association has to be in scope, so you'll need use schema::posts or similar to bring the table into scope, and use some_module::User if User were in a different module.

If the name of your foreign key doesn't follow the convention tablename_id, you can specify a custom one to #[belongs_to] by adding a foreign_key argument to the attribute like so #[belongs_to(Foo, foreign_key="mykey")].

Once the associations are defined, you can join between the two tables using the inner_join or left_outer_join.

let data: Vec<(User, Post)> = users::table.inner_join(posts::table).load(&connection);

Typically however, queries are loaded in multiple queries. For most datasets, the reduced amount of duplicated information sent over the wire saves more time than the extra round trip costs us. You can load the children for a single parent using the belonging_to

let user = try!(users::find(1).first(&connection));
let posts = Post::belonging_to(&user).load(&connection);

If you're coming from other ORMs, you'll notice that this design is quite different from most. There you would have an instance method on the parent, or have the children stored somewhere on the posts. This design leads to many problems, including N+1 query bugs, and runtime errors when accessing an association that isn't there.

In Diesel, data and its associations are considered to be separate. If you want to pass around a user and all of its posts, that type is (User, Vec<Post>).

Next lets look at how to load the children for more than one parent record. belonging_to can be used to load the data, but we'll also need to group it with its parents. For this we use an additional method grouped_by

fn first_twenty_users_and_their_posts(conn: &PgConnection) -> QueryResult<Vec<(User, Vec<Post>)>> {
    let users = try!(users::limit(20).load::<User>(conn));
    let posts = try!(Post::belonging_to(&users).load::<Post>(conn));
    let grouped_posts = posts.grouped_by(&users);

grouped_by takes a Vec<Child> and a Vec<Parent> and returns a Vec<Vec<Child>> where the index of the children matches the index of the parent they belong to. Or to put it another way, it returns them in an order ready to be ziped with the parents. You can do this multiple times. For example, if you wanted to load the comments for all the posts as well, you could do this: (explicit type annotations have been added for documentation purposes)

let posts: Vec<Post> = try!(Post::belonging_to(&users).load());
let comments: Vec<Comment> = try!(Comment::belonging_to(&posts).load());
let comments: Vec<Vec<Comment>> = comments.grouped_by(&posts);
let posts_and_comments: Vec<Vec<(Post, Vec<Comment>)>> = posts.into_iter().zip(comments).grouped_by(&users);
let result: Vec<(User, Vec<(Post, Vec<Comment>)>)> = users.into_iter().zip(posts_and_comments).collect();

And that's it. This module will be expanded in the future with more complex joins, and the ability to define "through" associations (e.g. load all the comments left on any posts written by a user in a single query). However, the goal is to provide simple building blocks which can be used to construct the complex behavior applications need.



Represents a struct which can be identified on a single table in the database. This must be implemented to use associations, and some features of updating. This trait is usually implemented on a reference to a struct, not the struct itself.