Trait diesel::associations::GroupedBy [] [src]

pub trait GroupedBy<'a, Parent>: IntoIterator + Sized {
    fn grouped_by(self, parents: &'a [Parent]) -> Vec<Vec<Self::Item>>;
}

The grouped_by function groups records by their parent.

grouped_by is called on a Vec<Child> with a &Vec<Parent> and returns a Vec<Vec<Child>> where the index of the children matches the index of the parent they belong to. This function does not generate a GROUP BY SQL statement, as it operates on data structures already loaded from the database backend.

Child refers to the many part of a one to many relationship and has one parent. Parent refers to the one part of a one to many relationship and can have many children. In the following relationship, User has many Posts, so User is the parent and Posts are children.

Example

let user_list = users.load::<User>(&connection).expect("Couldn't load users");
let post_list = posts.load::<Post>(&connection).expect("Couldn't load posts");

// Group Posts by Users
let posts_grouped_by_user: Vec<Vec<Post>> = post_list.grouped_by(&user_list);
let expected = vec![
    vec![
        Post { id: 1, user_id: 1, title: "My first post".to_string() },
        Post { id: 2, user_id: 1, title: "About Rust".to_string() }
    ],
    vec![
        Post { id: 3, user_id: 2, title: "My first post too".to_string() }
    ]
];

assert_eq!(posts_grouped_by_user, expected);

View the associations doc for more grouped_by() code examples

Required Methods

Implementors