Trait diesel::associations::GroupedBy
source · pub trait GroupedBy<'a, Parent>: IntoIterator + Sized {
// Required method
fn grouped_by(self, parents: &'a [Parent]) -> Vec<Vec<Self::Item>>;
}
Expand description
The grouped_by
function groups records by their parent.
grouped_by
is called on a Vec<Child>
with a &[Parent]
.
The return value will be Vec<Vec<Child>>
indexed to match their parent.
Or to put it another way, the returned data can be passed to zip
,
and it will be combined with its parent.
This function does not generate a GROUP BY
SQL statement,
as it operates on data structures already loaded from the database
Child refers to the “many” part of a “one to many” relationship. It “belongs to” its parent Parent refers to the “one” part of a “one to many” relationship and can “have many” children. The child always has a foreign key, which refers to its parent’s primary key. In the following relationship, User has many Posts, so User is the parent and Posts are children.
Example
let users = users::table.load::<User>(connection)?;
let posts = Post::belonging_to(&users)
.load::<Post>(connection)?
.grouped_by(&users);
let data = users.into_iter().zip(posts).collect::<Vec<_>>();
let expected_data = vec![
(
User { id: 1, name: "Sean".into() },
vec![
Post { id: 1, user_id: 1, title: "My first post".into() },
Post { id: 2, user_id: 1, title: "About Rust".into() },
],
),
(
User { id: 2, name: "Tess".into() },
vec![
Post { id: 3, user_id: 2, title: "My first post too".into() },
],
),
];
assert_eq!(expected_data, data);
See the module documentation for more examples