Model
in package
implements
JsonSerializable
Abstract ORM base class with query building, soft deletes, and automatic type casting
Comprehensive database model foundation for the Primordyx framework providing full ORM functionality with fluent query interfaces, automatic database introspection, soft delete support, validation integration, and JSON serialization. Features automatic timestamp management, type casting system, and seamless pagination support.
Core ORM Features
- Database Introspection: Automatic column discovery and caching via Cargo
- Soft Delete Support: Optional soft deletes with restore functionality
- Automatic Timestamps: created_at/updated_at management
- Type Casting System: Configurable attribute casting (bool, int, float, datetime)
- Fluent Query Builder: Chainable query methods with QueryBuilder integration
- Validation Integration: Validator system with error handling
- Change Tracking: Dirty field detection and original state preservation
- JSON Serialization: Built-in JsonSerializable implementation
- Pagination Support: Integrated pagination with Paginator class
- Bulk Operations: Bulk update capabilities with query constraints
Database Schema Requirements
Models expect standard conventions but allow override:
- Primary key:
id
(configurable via $primaryKey) - Table name: Class name + 's' (configurable via $table)
- Timestamps:
created_at
,updated_at
(if $timestamps = true) - Soft deletes:
deleted_at
,restored_at
(if $softDelete = true)
Query Builder Integration
Seamless integration with QueryBuilder for complex queries:
- Fluent interface with method chaining
- Query state preservation between operations
- Automatic soft delete filtering
- Support for raw queries and complex conditions
Type Casting System
Configurable attribute casting via $casts property:
bool
: Converts to 1/0 for database storageint
: Numeric validation with fallback to 0float
: Float conversion with fallback to 0.0datetime
: Converts DateTime objects and strings to Y-m-d H:i:s format
Tags
Attributes
- #[AllowDynamicProperties]
Table of Contents
Interfaces
- JsonSerializable
Properties
- $casts : array<string, string>
- Attribute type casting configuration array
- $data : array<string, mixed>
- Current model attribute data with type casting applied
- $db : PDO|null
- PDO database connection handle for all database operations
- $errors : array<string, array<string|int, string>>
- Validation and database error collection
- $includeSoftDeleted : bool
- Flag to include soft-deleted records in queries
- $original : array<string, mixed>
- Original attribute values for change detection
- $primaryKey : string
- Primary key column name for database operations
- $queryBuilder : QueryBuilder|null
- Current QueryBuilder instance for fluent query chaining
- $softDelete : bool
- Enable soft delete functionality for this model
- $table : string
- Database table name for the model
- $timestamps : bool
- Enable automatic timestamp management
Methods
- __construct() : mixed
- Initialize model with database introspection and attribute setup
- __get() : mixed
- Magic method to retrieve model attributes
- __isset() : bool
- Magic method to check if model attribute is set
- __set() : void
- Magic method to set model attributes with type casting
- andWhere() : static
- Alias for where() method providing explicit AND condition semantics
- asArray() : array<string, mixed>
- Alias for toArray() method providing consistent naming
- bulkUpdate() : int
- Perform bulk UPDATE operation on records matching current query conditions
- delete() : bool
- Remove record using soft delete or hard delete based on model configuration
- exists() : bool
- Check if model represents existing database record
- fill() : static
- Populate model attributes from associative array with type casting
- find() : static|null
- Find single record by primary key and populate current model instance
- findAll() : array<string|int, static>
- Retrieve all records from table as array of model instances
- findPage() : Paginator
- Alias for paginate() with consistent naming
- findPageAsModels() : Paginator
- Alias for paginateAsModels() with consistent naming
- first() : static|null
- Execute query and return first matching record as model instance
- forceDelete() : bool
- Permanently delete record from database regardless of soft delete setting
- getAsModels() : array<string|int, static>
- Execute current query and return results as model instances
- getDirty() : array<string, mixed>
- Get associative array of fields that have changed from original values
- getErrors() : array<string, array<string|int, string>>
- Retrieve all validation and database errors as associative array
- hasErrors() : bool
- Check if model has any validation or database errors
- isDirty() : bool
- Check if model has unsaved changes compared to original database state
- isValid() : bool
- Validate model data against defined rules and populate error array
- jsonSerialize() : array<string, mixed>
- JsonSerializable interface implementation for automatic JSON conversion
- limit() : static
- Add LIMIT clause to restrict number of returned records
- nextPageUrl() : string|null
- Generate URL for next page in pagination sequence
- offset() : static
- Add OFFSET clause to skip records at beginning of result set
- onlyTrashed() : array<string|int, array<string, mixed>>
- Get only soft-deleted records from the database
- orderBy() : static
- Add ORDER BY clause to query with column and direction
- orderByRaw() : static
- Add raw SQL ORDER BY clause to query
- orWhere() : static
- Add OR WHERE condition to query builder
- paginate() : Paginator
- Execute query with pagination and return raw data results
- paginateAsModels() : Paginator
- Execute query with pagination and return model instance results
- prevPageUrl() : string|null
- Generate URL for previous page in pagination sequence
- query() : QueryBuilder
- Create new QueryBuilder instance with automatic soft delete filtering
- reloadColumns() : void
- Force reload of table column information from database
- resetQueryBuilder() : static
- Clear current query builder state for fresh query building
- restore() : bool
- Restore soft-deleted record by clearing deleted_at timestamp
- rules() : array<string, string>
- Define validation rules for model attributes
- save() : bool
- Persist model changes to database with validation and timestamp management
- toArray() : array<string, mixed>
- Convert model data to associative array
- where() : static
- Add WHERE condition to query builder with flexible parameter support
- withTrashed() : static
- Include soft-deleted records in subsequent queries
- castAttribute() : mixed
- Apply configured type casting to attribute values
- insertRow() : bool
- Insert new record into database with column filtering and tracking
- table() : string
- Get the table name for this model with automatic generation fallback
- updateRow() : bool
- Update existing database record with only changed fields
Properties
$casts
Attribute type casting configuration array
protected
array<string, string>
$casts
= []
Defines how specific attributes should be cast when setting values. Supported types: 'bool' (to 1/0), 'int', 'float', 'datetime'. Override in child classes to specify casting rules for model attributes.
Attribute name => cast type mapping
Tags
$data
Current model attribute data with type casting applied
protected
array<string, mixed>
$data
= []
Stores all model attributes as key-value pairs after type casting via castAttribute(). Initialized with all table columns set to null during construction. Modified via magic methods __get/__set or direct array access.
Model attributes with applied type casting
Tags
$db
PDO database connection handle for all database operations
protected
PDO|null
$db
= null
Database connection used for all SQL operations. Defaults to ConnectionManager global connection but can be overridden via constructor parameter for multi-database scenarios or testing with specific connections.
Database connection or null to use default
Tags
$errors
Validation and database error collection
protected
array<string, array<string|int, string>>
$errors
= []
Stores validation errors from isValid() and database operation errors. Cleared on each validation run. Used by hasErrors() and getErrors() methods to provide error feedback after validation or save operations.
Error messages grouped by field/category
Tags
$includeSoftDeleted
Flag to include soft-deleted records in queries
protected
bool
$includeSoftDeleted
= false
When true, queries will include records with deleted_at timestamps. Modified by withTrashed() method to temporarily include soft-deleted records in query results. Resets to false for new queries.
Whether current query includes soft-deleted records
Tags
$original
Original attribute values for change detection
protected
array<string, mixed>
$original
= []
Preserves the initial state of model data after loading from database or after successful save operations. Used by isDirty() and getDirty() methods to detect field changes and optimize update queries.
Original model state for change tracking
Tags
$primaryKey
Primary key column name for database operations
protected
string
$primaryKey
= 'id'
Defines the primary key field used for find, update, and delete operations. Must be a unique identifier column in the database table. Used for exists() checking and WHERE clauses in update/delete operations.
Primary key column name
Tags
$queryBuilder
Current QueryBuilder instance for fluent query chaining
protected
QueryBuilder|null
$queryBuilder
= null
Preserves query state between fluent method calls. Set by query methods like where(), orderBy(), limit() to maintain query context. Reset after query execution or via resetQueryBuilder() method.
Current query builder or null for fresh queries
Tags
$softDelete
Enable soft delete functionality for this model
protected
bool
$softDelete
= true
When true, delete() operations set deleted_at timestamp instead of removing records. Automatic filtering excludes soft-deleted records from queries unless specifically included via withTrashed() or onlyTrashed() methods.
Whether to use soft deletes (true) or hard deletes (false)
Tags
$table
Database table name for the model
protected
string
$table
= ''
Specifies which database table this model represents. Defaults to empty string, which triggers automatic table name generation based on class name (class + 's'). Override in child classes to specify explicit table names.
Database table name or empty for auto-generation
Tags
$timestamps
Enable automatic timestamp management
protected
bool
$timestamps
= true
When true, automatically manages created_at and updated_at fields during save operations. Sets created_at on insert and updated_at on all saves. Requires corresponding datetime columns in database table.
Whether to automatically manage timestamps
Tags
Methods
__construct()
Initialize model with database introspection and attribute setup
public
__construct([array<string, mixed> $attrs = [] ][, PDO|null $db = null ][, string|null $table = null ][, string|null $primaryKey = null ]) : mixed
Creates new model instance with automatic database column discovery, caching, and attribute initialization. Performs database introspection to determine available columns and initializes all columns to null before applying provided attributes.
Initialization Process
- Sets database connection (parameter or ConnectionManager default)
- Overrides table/primaryKey if provided
- Checks Cargo cache for table columns
- Performs DESCRIBE query if columns not cached
- Caches column list for future use
- Initializes all columns to null in $data array
- Applies provided attributes via fill()
- Captures original state for change tracking
Column Caching
Uses Cargo caching with key format: 'model.columns.{table_name}' Reduces database queries by caching DESCRIBE results Automatically handles cache invalidation via reloadColumns()
Parameters
- $attrs : array<string, mixed> = []
-
Initial attribute values to fill
- $db : PDO|null = null
-
Database connection override (null uses ConnectionManager)
- $table : string|null = null
-
Table name override (null uses model default)
- $primaryKey : string|null = null
-
Primary key override (null uses model default)
Tags
__get()
Magic method to retrieve model attributes
public
__get(string $key) : mixed
Provides object-like access to model data array. Returns null for non-existent attributes rather than throwing errors for graceful handling of undefined properties.
Parameters
- $key : string
-
Attribute name to retrieve
Tags
Return values
mixed —Attribute value or null if not set
__isset()
Magic method to check if model attribute is set
public
__isset(string $key) : bool
Returns true if the attribute exists and is not null in the data array. Enables use of isset() and empty() with model attributes.
Parameters
- $key : string
-
Attribute name to check
Tags
Return values
bool —True if attribute is set and not null
__set()
Magic method to set model attributes with type casting
public
__set(string $key, mixed $value) : void
Applies configured type casting via castAttribute() before storing values in the data array. Provides object-like attribute assignment with automatic type conversion.
Parameters
- $key : string
-
Attribute name to set
- $value : mixed
-
Raw value to cast and store
Tags
andWhere()
Alias for where() method providing explicit AND condition semantics
public
andWhere(mixed ...$args) : static
Functionally identical to where() but provides clearer intent when building complex queries with multiple conditions. All WHERE conditions are combined with AND by default.
Parameters
- $args : mixed
-
Variable arguments for WHERE condition
Tags
Return values
static —Current model instance for method chaining
asArray()
Alias for toArray() method providing consistent naming
public
asArray() : array<string, mixed>
Identical functionality to toArray() with alternative method name for consistency across different coding styles and preferences.
Tags
Return values
array<string, mixed> —All model attributes as associative array
bulkUpdate()
Perform bulk UPDATE operation on records matching current query conditions
public
bulkUpdate(array<string, mixed> $data) : int
Updates multiple records with provided data based on current QueryBuilder conditions. Applies automatic timestamp management and type casting. Resets query builder after execution and returns number of affected rows.
Update Process
- Validates data array is not empty
- Gets WHERE conditions from current QueryBuilder
- Adds updated_at timestamp if timestamps enabled
- Applies type casting to all values
- Builds and executes UPDATE SQL
- Returns count of affected rows
- Resets QueryBuilder state
Performance Benefits
- Single SQL operation vs multiple save() calls
- Reduced database round trips
- Automatic WHERE clause building from query conditions
- Consistent type casting and timestamp management
Parameters
- $data : array<string, mixed>
-
Field values to update across matched records
Tags
Return values
int —Number of database rows affected by update
delete()
Remove record using soft delete or hard delete based on model configuration
public
delete() : bool
Removes record from active dataset using either soft delete (sets deleted_at) or hard delete (removes from database) based on $softDelete property setting. Returns false if model doesn't have primary key value.
Soft Delete Behavior
- Sets deleted_at timestamp to current datetime
- Preserves record in database for recovery
- Automatically excluded from future queries
- Enables restore() functionality
Hard Delete Behavior
- Permanently removes record from database
- Cannot be recovered after deletion
- Used when $softDelete = false
Tags
Return values
bool —True if deletion successful, false if no primary key or database error
exists()
Check if model represents existing database record
public
exists() : bool
Determines if current model instance represents an existing database record by checking for non-empty primary key value. Used internally by save() to decide between INSERT and UPDATE operations.
Tags
Return values
bool —True if primary key has value (existing record), false if empty (new record)
fill()
Populate model attributes from associative array with type casting
public
fill(array<string, mixed> $attrs) : static
Fills model data array with provided attributes, applying configured type casting to each value. Enables mass assignment of attributes with proper type conversion and validation.
Parameters
- $attrs : array<string, mixed>
-
Associative array of attribute values
Tags
Return values
static —Current model instance for method chaining
find()
Find single record by primary key and populate current model instance
public
find(mixed $id) : static|null
Loads record data into the current model instance and updates original state for change tracking. Returns the model instance for method chaining or null if record not found.
State Management
- Populates $data array with record fields
- Updates $original array for change tracking
- Enables immediate save() operations after modifications
- Respects soft delete settings
Parameters
- $id : mixed
-
Primary key value to search for
Tags
Return values
static|null —Current model instance if found, null if not found
findAll()
Retrieve all records from table as array of model instances
public
findAll() : array<string|int, static>
Loads all non-soft-deleted records from the model's table and returns them as an array of new model instances. Each instance is fully populated and ready for individual operations.
Tags
Return values
array<string|int, static> —Array of model instances for all records
findPage()
Alias for paginate() with consistent naming
public
findPage([int $perPage = 15 ][, int $page = 1 ]) : Paginator
Provides alternative method name for pagination with raw data arrays. Identical functionality to paginate() with more explicit naming.
Parameters
- $perPage : int = 15
-
Number of records per page
- $page : int = 1
-
Current page number (1-based)
Tags
Return values
Paginator —Pagination results with raw data
findPageAsModels()
Alias for paginateAsModels() with consistent naming
public
findPageAsModels([int $perPage = 15 ][, int $page = 1 ]) : Paginator
Provides alternative method name for pagination with model instances. Identical functionality to paginateAsModels() with more explicit naming.
Parameters
- $perPage : int = 15
-
Number of records per page
- $page : int = 1
-
Current page number (1-based)
Tags
Return values
Paginator —Pagination results with model instances
first()
Execute query and return first matching record as model instance
public
first() : static|null
Returns the first record matching current query conditions as a populated model instance. Returns null if no records match the query conditions. Automatically applies LIMIT 1 for performance optimization.
Tags
Return values
static|null —Model instance for first matching record or null if none found
forceDelete()
Permanently delete record from database regardless of soft delete setting
public
forceDelete() : bool
Performs hard DELETE operation that permanently removes record from database. Bypasses soft delete configuration and cannot be recovered. Use with caution as this operation is irreversible.
Tags
Return values
bool —True if permanent deletion successful, false if no primary key or database error
getAsModels()
Execute current query and return results as model instances
public
getAsModels() : array<string|int, static>
Runs the built query (or basic select if no query builder) and converts each result row into a new model instance. Provides object-oriented access to result data with all model functionality.
Tags
Return values
array<string|int, static> —Array of model instances from query results
getDirty()
Get associative array of fields that have changed from original values
public
getDirty() : array<string, mixed>
Returns key-value pairs of only the fields that differ between current model data and original database state. Useful for partial updates and change logging.
Tags
Return values
array<string, mixed> —Changed fields with their current values
getErrors()
Retrieve all validation and database errors as associative array
public
getErrors() : array<string, array<string|int, string>>
Returns complete error array with field names as keys and error message arrays as values. Includes both validation errors from isValid() and database operation errors from save/delete operations.
Tags
Return values
array<string, array<string|int, string>> —Error messages grouped by field/category
hasErrors()
Check if model has any validation or database errors
public
hasErrors() : bool
Returns true if the errors array contains any error messages from validation failures or database operation errors. Useful for conditional logic based on model error state.
Tags
Return values
bool —True if errors exist, false if error-free
isDirty()
Check if model has unsaved changes compared to original database state
public
isDirty([string|null $field = null ]) : bool
Compares current model data with original values to detect modifications. Can check entire model or specific field for changes. Returns true if any differences are found between current and original state.
Parameters
- $field : string|null = null
-
Specific field to check, or null for entire model
Tags
Return values
bool —True if model/field has unsaved changes, false if unchanged
isValid()
Validate model data against defined rules and populate error array
public
isValid() : bool
Runs model data through Validator system using rules from rules() method. Clears previous errors and populates $errors array with any validation failures. Returns true only if all validations pass.
Validation Process
- Clears existing error array
- Gets validation rules from rules() method
- Runs Validator::validate() on current data
- Populates $errors array with failures
- Returns true if no errors found
Tags
Return values
bool —True if all validations pass, false if any validation fails
jsonSerialize()
JsonSerializable interface implementation for automatic JSON conversion
public
jsonSerialize() : array<string, mixed>
Enables automatic JSON serialization when model is passed to json_encode(). Returns model data array for consistent JSON representation of model objects in API responses and data serialization.
Tags
Return values
array<string, mixed> —Model data for JSON serialization
limit()
Add LIMIT clause to restrict number of returned records
public
limit(int $limit) : static
Limits query results to specified number of records. Commonly used with orderBy() for top-N queries or with offset() for pagination.
Parameters
- $limit : int
-
Maximum number of records to return
Tags
Return values
static —Current model instance for method chaining
nextPageUrl()
Generate URL for next page in pagination sequence
public
nextPageUrl(int $perPage, int $currentPage, int $totalPages, string $baseUrl[, array<string, mixed> $extraParams = [] ]) : string|null
Creates properly formatted URL for the next page with pagination parameters and optional additional query parameters. Returns null if already on last page.
Parameters
- $perPage : int
-
Items per page for URL parameters
- $currentPage : int
-
Current page number for calculation
- $totalPages : int
-
Total available pages for boundary checking
- $baseUrl : string
-
Base URL without query parameters
- $extraParams : array<string, mixed> = []
-
Additional query parameters to include
Tags
Return values
string|null —Next page URL or null if on last page
offset()
Add OFFSET clause to skip records at beginning of result set
public
offset(int $offset) : static
Skips specified number of records before returning results. Primarily used with limit() for manual pagination implementation. Results depend on consistent ordering for predictable pagination.
Parameters
- $offset : int
-
Number of records to skip
Tags
Return values
static —Current model instance for method chaining
onlyTrashed()
Get only soft-deleted records from the database
public
onlyTrashed() : array<string|int, array<string, mixed>>
Returns array of records that have been soft-deleted (deleted_at IS NOT NULL). Provides direct access to deleted records without affecting model query state.
Tags
Return values
array<string|int, array<string, mixed>> —Array of deleted record data
orderBy()
Add ORDER BY clause to query with column and direction
public
orderBy(string $column[, string $direction = 'ASC' ]) : static
Sorts query results by specified column and direction. Preserves query state and allows multiple orderBy calls for complex sorting requirements.
Parameters
- $column : string
-
Database column name to sort by
- $direction : string = 'ASC'
-
Sort direction: 'ASC' or 'DESC' (default: 'ASC')
Tags
Return values
static —Current model instance for method chaining
orderByRaw()
Add raw SQL ORDER BY clause to query
public
orderByRaw(string $clause) : static
Allows complex ordering with raw SQL expressions, functions, and calculations. Provides maximum flexibility for advanced sorting requirements beyond simple column ordering.
Parameters
- $clause : string
-
Raw SQL ORDER BY clause (without ORDER BY keyword)
Tags
Return values
static —Current model instance for method chaining
orWhere()
Add OR WHERE condition to query builder
public
orWhere(mixed ...$args) : static
Adds OR condition to existing WHERE clause. Requires existing query builder state with previous conditions to combine with OR logic. Maintains query state for continued method chaining.
Parameters
- $args : mixed
-
Variable arguments for OR WHERE condition
Tags
Return values
static —Current model instance for method chaining
paginate()
Execute query with pagination and return raw data results
public
paginate([int $perPage = 15 ][, int $page = 1 ]) : Paginator
Performs paginated query execution returning raw associative arrays. Provides pagination metadata through Paginator object including total count, page information, and navigation helpers.
Parameters
- $perPage : int = 15
-
Number of records per page
- $page : int = 1
-
Current page number (1-based)
Tags
Return values
Paginator —Pagination results with raw data arrays
paginateAsModels()
Execute query with pagination and return model instance results
public
paginateAsModels([int $perPage = 15 ][, int $page = 1 ]) : Paginator
Performs paginated query execution and converts each result row into a model instance. Combines pagination functionality with object-oriented result access for comprehensive data handling.
Parameters
- $perPage : int = 15
-
Number of records per page
- $page : int = 1
-
Current page number (1-based)
Tags
Return values
Paginator —Pagination results with model instances
prevPageUrl()
Generate URL for previous page in pagination sequence
public
prevPageUrl(int $perPage, int $currentPage, string $baseUrl[, array<string, mixed> $extraParams = [] ]) : string|null
Creates properly formatted URL for the previous page with pagination parameters and optional additional query parameters. Returns null if already on first page.
Parameters
- $perPage : int
-
Items per page for URL parameters
- $currentPage : int
-
Current page number for calculation
- $baseUrl : string
-
Base URL without query parameters
- $extraParams : array<string, mixed> = []
-
Additional query parameters to include
Tags
Return values
string|null —Previous page URL or null if on first page
query()
Create new QueryBuilder instance with automatic soft delete filtering
public
query() : QueryBuilder
Initializes fresh QueryBuilder for the model's table with automatic soft delete exclusion if enabled. Provides foundation for all query operations with consistent filtering behavior.
Automatic Filtering
- Applies 'deleted_at IS NULL' condition if soft deletes enabled
- Respects $includeSoftDeleted flag from withTrashed() method
- Provides clean base for additional query conditions
Tags
Return values
QueryBuilder —Fresh query builder instance for this model
reloadColumns()
Force reload of table column information from database
public
reloadColumns() : void
Performs fresh DESCRIBE query on the model's table and updates the Cargo cache with current column information. Useful after schema changes or when cache becomes stale.
Cache Management
- Clears existing cached columns for this table
- Executes DESCRIBE query with QueryTracker monitoring
- Updates Cargo cache with fresh column list
- Provides foundation for accurate introspection
Tags
resetQueryBuilder()
Clear current query builder state for fresh query building
public
resetQueryBuilder() : static
Resets the query builder to null, allowing subsequent query methods to start with a clean slate. Useful when reusing model instances for multiple different queries.
Tags
Return values
static —Current model instance for method chaining
restore()
Restore soft-deleted record by clearing deleted_at timestamp
public
restore() : bool
Recovers previously soft-deleted record by setting deleted_at to null and recording restoration timestamp. Only works with soft delete enabled models that have been previously deleted.
Restoration Process
- Sets deleted_at field to null
- Sets restored_at timestamp to current datetime
- Record becomes visible in normal queries again
- Triggers save() operation to persist changes
Tags
Return values
bool —True if restoration successful, false if not soft delete model or no primary key
rules()
Define validation rules for model attributes
public
rules() : array<string, string>
Override this method in child classes to specify validation rules for model attributes. Rules are used by isValid() method through the Validator system for data validation before save operations.
Tags
Return values
array<string, string> —Attribute validation rules
save()
Persist model changes to database with validation and timestamp management
public
save() : bool
Validates model data, manages timestamps, and performs INSERT or UPDATE based on model state. Returns true on success, false on validation failure or database error.
Save Process
- Runs validation via isValid() method
- Updates timestamp fields if enabled
- Determines INSERT vs UPDATE based on exists()
- Executes appropriate database operation
- Updates model state on success
Timestamp Management
- Sets updated_at on all save operations
- Sets created_at only on new record creation
- Uses current datetime in Y-m-d H:i:s format
Tags
Return values
bool —True if save successful, false if validation failed or database error
toArray()
Convert model data to associative array
public
toArray() : array<string, mixed>
Returns the complete model data array with all attribute values. Useful for serialization, API responses, and data transformation operations where array format is required.
Tags
Return values
array<string, mixed> —All model attributes as associative array
where()
Add WHERE condition to query builder with flexible parameter support
public
where(mixed ...$args) : static
Supports both standard where conditions and raw SQL strings. Initializes query builder if needed and preserves query state for method chaining. Handles multiple parameter formats for maximum flexibility.
Parameter Formats
- Single string: Raw SQL condition
- Multiple parameters: Standard where($column, $operator, $value) or where($column, $value)
Parameters
- $args : mixed
-
Variable arguments for WHERE condition
Tags
Return values
static —Current model instance for method chaining
withTrashed()
Include soft-deleted records in subsequent queries
public
withTrashed() : static
Modifies the model state to include records with deleted_at timestamps in query results. Only affects the current model instance and resets after query execution.
Tags
Return values
static —Current model instance for method chaining
castAttribute()
Apply configured type casting to attribute values
protected
castAttribute(string $field, mixed $value) : mixed
Converts attribute values based on the $casts configuration array. Provides consistent type handling across all attribute operations with fallback values for invalid input data.
Supported Cast Types
- bool: Uses filter_var(FILTER_VALIDATE_BOOLEAN), returns 1/0 for database
- int: Validates numeric input, returns 0 for non-numeric values
- float: Validates numeric input, returns 0.0 for non-numeric values
- datetime: Converts DateTime objects and strings to 'Y-m-d H:i:s' format
Type Safety
Invalid values are converted to safe defaults rather than causing errors:
- Non-boolean values become 0 (false) for bool type
- Non-numeric values become 0 for int type
- Non-numeric values become 0.0 for float type
- Invalid datetime strings use strtotime() for parsing
Parameters
- $field : string
-
Attribute name to check for casting configuration
- $value : mixed
-
Raw value to apply casting to
Tags
Return values
mixed —Casted value or original value if no casting defined
insertRow()
Insert new record into database with column filtering and tracking
protected
insertRow() : bool
Performs INSERT operation for new records with automatic column validation, query tracking, and primary key assignment. Filters data to only include columns that exist in the database table.
Insert Process
- Gets cached table columns from Cargo
- Filters model data to only valid columns
- Builds parameterized INSERT SQL
- Executes with QueryTracker monitoring
- Sets primary key from lastInsertId()
- Updates original state for change tracking
- Records database errors if operation fails
Tags
Return values
bool —True if insert successful, false on database error
table()
Get the table name for this model with automatic generation fallback
protected
table() : string
Returns the configured table name or generates one from the class name. Generation rule: lowercase class name + 's' suffix. Provides consistent table naming across the application.
Tags
Return values
string —Database table name for this model
updateRow()
Update existing database record with only changed fields
protected
updateRow() : bool
Performs UPDATE operation using only dirty (changed) fields for performance optimization. Uses change tracking to minimize database operations and avoid unnecessary updates.
Update Process
- Gets dirty fields via getDirty()
- Returns true immediately if no changes
- Builds UPDATE SQL with only changed fields
- Executes with WHERE primary key condition
- Executes with QueryTracker monitoring
- Updates original state on success
- Records database errors if operation fails
Tags
Return values
bool —True if update successful or no changes needed, false on database error