Skip to main content

BatchLoad

Trait BatchLoad 

Source
pub trait BatchLoad: EntityTrait + Sized
where Self::Model: Send + Sync,
{ 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§

Source

type Key: Clone + Eq + Hash + Send + Sync

The type of the primary key used for lookups

Required Methods§

Source

fn extract_pk(model: &Self::Model) -> Self::Key

Extract the primary key value from a model

Source

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,

Batch load multiple entities by their primary keys

Returns a HashMap for O(1) lookups by primary key.

§Example
let ids = vec![1, 2, 3, 4, 5];
let shelters = Shelter::batch_load(ids).await?;
let shelter = shelters.get(&1);

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.

Implementors§