Skip to main content

ScopedQuery

Trait ScopedQuery 

Source
pub trait ScopedQuery: EntityTrait + Sized
where Self::Model: Send + Sync,
{ type Scope: Scope<Self>; // Provided methods fn scoped(scope: Self::Scope) -> ScopedQueryBuilder<Self> { ... } fn for_owner<C, V>(owner_id: V, column: C) -> QueryBuilder<Self> where C: ColumnTrait, V: Into<Value> { ... } }
Expand description

Trait for defining reusable query scopes on entities

Implement this trait to define common filters that can be applied to queries in a chainable, reusable way.

§Example

use ferro_rs::database::{ScopedQuery, Scope};

// Define scopes for your entity
pub enum AnimalScope {
    ForShelter(i64),
    Available,
    Species(String),
    Size(String),
}

impl Scope<animals::Entity> for AnimalScope {
    fn apply(self, query: QueryBuilder<animals::Entity>) -> QueryBuilder<animals::Entity> {
        use animals::Column;
        match self {
            Self::ForShelter(id) => query.filter(Column::ShelterId.eq(id)),
            Self::Available => query.filter(Column::Status.eq("available")),
            Self::Species(s) => query.filter(Column::Species.eq(s)),
            Self::Size(s) => query.filter(Column::Size.eq(s)),
        }
    }
}

// Implement ScopedQuery for your entity
impl ScopedQuery for animals::Entity {
    type Scope = AnimalScope;
}

// Now use scopes in queries:
let dogs = Animal::scoped(AnimalScope::Species("dog".into()))
    .and(AnimalScope::Available)
    .all()
    .await?;

Required Associated Types§

Source

type Scope: Scope<Self>

The scope type for this entity

Provided Methods§

Source

fn scoped(scope: Self::Scope) -> ScopedQueryBuilder<Self>

Start a query with the given scope applied

Source

fn for_owner<C, V>(owner_id: V, column: C) -> QueryBuilder<Self>
where C: ColumnTrait, V: Into<Value>,

Start a query for records belonging to a specific owner

This is a convenience method for common “for_user” or “for_owner” patterns.

§Example
// If your entity has a user_id column
let user_favorites = Favorite::for_owner(user.id, Column::UserId).all().await?;

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§