pub trait BatchLoad: EntityTrait + Sized{
type Key: Clone + Eq + Hash + Send + Sync;
// Required methods
fn extract_pk(model: &Self::Model) -> Self::Key;
fn batch_load<'async_trait, I>(
ids: I,
) -> Pin<Box<dyn Future<Output = Result<HashMap<Self::Key, Self::Model>, FrameworkError>> + Send + 'async_trait>>
where I: IntoIterator<Item = Self::Key> + Send + 'async_trait,
I::IntoIter: Send,
Self: 'async_trait;
}Expand description
Trait for batch loading entities by their primary key
Implement this on your entity to enable batch loading, which helps avoid N+1 query problems when loading related entities.
§Example
ⓘ
// Instead of N+1 queries:
for animal in &animals {
let shelter = Shelter::find_by_pk(animal.shelter_id).await?; // N queries!
}
// Use batch loading (1 query):
let shelter_ids: Vec<_> = animals.iter().map(|a| a.shelter_id).collect();
let shelters = Shelter::batch_load(shelter_ids).await?;
for animal in &animals {
let shelter = shelters.get(&animal.shelter_id);
}Required Associated Types§
Required Methods§
Sourcefn extract_pk(model: &Self::Model) -> Self::Key
fn extract_pk(model: &Self::Model) -> Self::Key
Extract the primary key value from a model
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.