-
BackendMySQL Diesel version2.3.5 Diesel Featuresmysql Operating System VersionDebian 13 Third party librariesserde="1.0.228" What do you want to do?In the Relations guide there's an example of using #[derive(Serialize)]
struct BookWithPages {
#[serde(flatten)]
book: Book,
pages: Vec<Page>,
}
// First query
let all_books = books::table.select(Book::as_select()).load(conn)?;
// Second query
// get all pages for all books
let pages = Page::belonging_to(&all_books)
.select(Page::as_select())
.load(conn)?;
// group the pages per book
let pages_per_book = pages
.grouped_by(&all_books)
.into_iter()
.zip(all_books)
.map(|(pages, book)| BookWithPages { book, pages })
.collect::<Vec<BookWithPages>>();There will be two SQL queries there. Later, when covering let page_with_book = pages::table
.inner_join(books::table)
.filter(books::title.eq("Momo"))
.select((Page::as_select(), Book::as_select()))
.load::<(Page, Book)>(conn)?;My question is, is there an easy way to use the latter Perhaps this is more of a general Rust data structures question than a Diesel question since I do appreciate that what is doing the work in the first example is the "group the pages per book" step, but I don't know enough to know, as I am a bit new at Rust in general. Naively, all the data are there so I suppose one could just iterate through the Thanks! Compile time errorNo response What code do you already have?No response Additional detailsNo response Checklist
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
That's what needs to be done. There is no way to skip this work. Diesel doesn't currently provide any API for this, so you need to roll your own implementation. To do this you would need roughly the following:
I would like to comment on this: Yes there will be two queries, but at the same time you don't transmit any duplicated data. So depending on the exact data you request two queries might be faster than one in this particular case. |
Beta Was this translation helpful? Give feedback.
That's what needs to be done. There is no way to skip this work. Diesel doesn't currently provide any API for this, so you need to roll your own implementation.
To do this you would need roughly the following:
HashMap<i32, (Book, Vec<Page>)>(Book, Page)pairs and: