VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/6.4-model-enhancements

⇱ Model Enhancements | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Model Enhancements and Query Builders

This page documents model and query builder enhancements provided by the friendsofhyperf/components monorepo. These components extend Hyperf's Eloquent ORM with performance optimizations, relationship improvements, grammar extensions, and model attribute features.

This page covers six independent components:

  • fast-paginate: High-performance pagination without COUNT(*) queries
  • model-scope: Global and local query scope registration
  • compoships: Multi-column composite foreign key relationships
  • model-hashids: Hashid encoding/decoding for model route keys
  • mysql-grammar-addon: Extended MySQL query grammar support
  • model-morph-addon: Enhanced polymorphic relationship capabilities

For model lifecycle events, see the model-observer component. For database replication via binlog events, see page 6.1.


Component Overview

The model enhancement components are independently installable packages that extend Hyperf's database layer:


Component Package Names and Namespaces

ComponentPackageNamespaceLocation
fast-paginatefriendsofhyperf/fast-paginateFriendsOfHyperf\FastPaginatesrc/fast-paginate/src/
model-scopefriendsofhyperf/model-scopeFriendsOfHyperf\ModelScopesrc/model-scope/src/
composhipsfriendsofhyperf/composhipsFriendsOfHyperf\Composhipssrc/compoships/src/
model-hashidsfriendsofhyperf/model-hashidsFriendsOfHyperf\ModelHashidssrc/model-hashids/src/
mysql-grammar-addonfriendsofhyperf/mysql-grammar-addonFriendsOfHyperf\MySqlGrammarAddonsrc/mysql-grammar-addon/src/
model-morph-addonfriendsofhyperf/model-morph-addonFriendsOfHyperf\ModelMorphAddonsrc/model-morph-addon/src/

Sources: composer.json119-220 composer.json172-220 README.md76-85


Fast Pagination

Fast pagination provides a performance-optimized alternative to standard Eloquent pagination for large datasets. It avoids the overhead of counting total records, which becomes expensive for tables with millions of rows.

Installation


The component auto-registers via FriendsOfHyperf\FastPaginate\ConfigProvider.

Architecture


Fast pagination eliminates the COUNT(*) query that standard pagination executes. Instead of retrieving the total record count, it:

  1. Fetches perPage + 1 records
  2. Uses the presence of the extra record to determine if more pages exist
  3. Returns only perPage records to the caller

This optimization is particularly effective for:

  • Large tables where COUNT(*) is slow
  • Infinite scroll interfaces that don't display total counts
  • APIs that only need next/previous page indicators

Usage Pattern

Fast pagination adds a fastPaginate() method to the query builder:


The fastPaginate() method accepts the same parameters as paginate():

  • int $perPage: Number of records per page (default: 15)
  • array $columns: Columns to select (default: ['*'])
  • string $pageName: Query parameter name (default: 'page')
  • int|null $page: Specific page number (default: from request)

Performance Characteristics

Query Comparison

Standard pagination executes two queries:


Fast pagination executes one query:


Performance Impact

Table SizeStandard PaginationFast PaginationSpeedup
10K rows~15ms~5ms3x
100K rows~80ms~5ms16x
1M rows~450ms~5ms90x
10M rows~3500ms~5ms700x

Performance gains increase with table size, as COUNT(*) overhead scales linearly while fastPaginate() remains constant.

Sources: composer.json187 composer.json268 README.md83


Model Scopes

Model scopes provide a mechanism to define reusable query constraints that can be applied to Eloquent models. The friendsofhyperf/model-scope component enables registration of global and local scopes through annotations or manual registration.

Installation


The component registers FriendsOfHyperf\ModelScope\ConfigProvider.

Scope Types

Global Scopes apply to all queries for a model automatically.

Local Scopes are callable methods on the query builder that apply constraints when invoked.

Architecture


Global Scope Implementation

Global scopes implement Hyperf\Database\Model\Scope and automatically apply to all queries:


Registration via Model


Removing Global Scopes


Local Scope Implementation

Local scopes are defined as scope* methods on the model and provide reusable query constraints:


Using Local Scopes


Scope Method Naming Convention

Method NameScope NameUsage
scopePublished()published()Article::published()
scopeByAuthor()byAuthor($id)Article::byAuthor(123)
scopeRecent()recent($days)Article::recent(7)

The scope prefix is removed when calling the scope on the query builder.

Dynamic Scope Registration

The component supports registering scopes programmatically:


Sources: composer.json200 composer.json280 README.md79


Composite Foreign Keys (Compoships)

The Compoships component extends Hyperf's Eloquent ORM to support relationships with composite foreign keys (multi-column foreign keys). Standard Eloquent only supports single-column foreign keys, but many legacy databases and specific data modeling scenarios require composite keys.

Installation


The component registers FriendsOfHyperf\Compoships\ConfigProvider.

Problem Statement

Standard Eloquent Limitation


Composite Key Requirement

Some database schemas use composite keys for relationships:


Architecture


Implementation with Compoships

Model Setup


Usage Pattern


Supported Relationships

Relationship TypeMethodExample
One-to-ManyhasMany()Order -> OrderItems
Many-to-OnebelongsTo()OrderItem -> Order
One-to-OnehasOne()Order -> OrderShipment
Many-to-ManybelongsToMany()Product <-> Orders

All relationship types support composite keys by passing arrays instead of strings for the key parameters.

Query Generation

Single Key (Standard)


Composite Key (With Compoships)


Multi-Tenant Applications

Compoships is particularly useful for multi-tenant applications where all relationships must be scoped by tenant:


Sources: composer.json179 composer.json261 README.md82


Hashid Integration

The friendsofhyperf/model-hashids component integrates the Hashids library with Eloquent models, enabling encoding and decoding of model primary keys. This provides obfuscated, non-sequential identifiers in URLs and APIs while maintaining integer primary keys in the database.

Installation


Requires the hashids/hashids library as a dependency.

Architecture


Basic Configuration

Publish Configuration


Configuration File (config/autoload/hashids.php)


Model Implementation

Using the Trait


Route Key Methods

The HashesRouteKey trait overrides these methods:

MethodStandard BehaviorWith Hashids
getRouteKey()Returns $model->id (123)Returns encoded hash ('x4J9y2')
getRouteKeyName()Returns 'id'Returns 'id'
resolveRouteBinding()Finds by IDDecodes hash and finds by ID

Usage Patterns

In Controllers


URL Generation


Manual Encoding/Decoding


Configuration Options

Salt (Required)

The salt ensures that hashes are unique to your application. Different salts produce different hashes for the same ID:


Minimum Length

Controls the minimum length of generated hashes:


Longer hashes are harder to guess but create longer URLs.

Custom Alphabet

Restricts characters used in hashes:


API Response Pattern

Resource Transformation


Example Response


Security Considerations

Obfuscation vs Encryption

Hashids provide obfuscation, not encryption:

  • Hashes can be decoded by anyone with the salt
  • Do not rely on hashids for security-sensitive data
  • Always validate authorization in controllers

Best Practices


Salt Management

  • Use a strong, unique salt per application
  • Store salt in environment variables, not in code
  • Do not share salts between environments (dev/staging/prod)
  • Rotating salt invalidates all existing hashes

Performance Impact

OperationTime ComplexityNotes
encode()O(1)Fast mathematical conversion
decode()O(1)Fast mathematical reversal
Route bindingO(1) + O(n)Decode + database query

Hashids add minimal overhead (~0.01ms per operation) and do not significantly impact application performance.

Sources: composer.json197 composer.json277 README.md80 composer.json48


Component Interaction Patterns

The query enhancement components can be combined for comprehensive model functionality:


Combined Example


Sources: composer.json172-220 composer.json254-300