This reference documents the public API of Freshsauce\Model\Model as implemented in src/Model/Model.php.
These are the static members you are expected to override in subclasses.
Required. The database table for the model.
protected static $_tableName = 'categories';Optional. Defaults to id.
protected static $_primary_column_name = 'code';Optional. Defaults to false. When enabled, unknown assignments throw UnknownFieldException.
Optional. Defaults to true. Set to false to disable built-in automatic timestamp handling for the model.
Optional. Defaults to created_at. Set to a different column name to customise insert timestamps, or null to disable created-at writes.
Optional. Defaults to updated_at. Set to a different column name to customise insert/update timestamps, or null to disable updated-at writes.
Optional. Field cast map. Supported cast types are integer, float, boolean, datetime, array, and object.
For datetime, string values are interpreted as UTC wall-time values. Prefer DATETIME-style columns, or ensure the connection session timezone is UTC when using database types that perform timezone conversion.
Inherited shared PDO connection. Redeclare this in a subclass only when that subclass needs an isolated connection.
Initialises the model and hydrates known columns from the provided array.
Returns whether the internal data object exists.
Returns true when data is present, otherwise throws MissingDataException.
Maps known table columns from the input array onto the model. Unknown keys are ignored.
Sets all known columns to null and resets dirty tracking.
Returns an associative array of known table columns and their current values.
Marks a field dirty manually.
Returns whether a field is dirty.
Clears the dirty-field tracking state.
Serialises the data and dirty properties.
Returns a normalised serialisable payload containing data and dirty.
Restores serialised model state.
Assigns a value to the model.
Behavior:
- in strict mode, resolves the name against real fields first
- creates the internal data object on first assignment
- applies configured attribute casts before storing the value
- marks the field as dirty
Returns a field value from the internal data store.
When a field is configured in $_casts, the returned value is the cast PHP value.
Throws:
MissingDataExceptionwhen data has not been initialisedUnknownFieldExceptionwhen the field is not present in the current data object
Returns whether the current data object contains the field.
Creates and stores the PDO connection for the current model class hierarchy.
Notes:
- sets
PDO::ATTR_ERRMODEtoPDO::ERRMODE_EXCEPTION - clears cached prepared statements for the previous connection
- clears cached column metadata
Returns the active PDO driver name.
Clears the cached table-column list for the current model class.
Use this after runtime schema changes.
Prepares and executes a statement, returning the PDOStatement.
Begins a transaction on the current model connection.
Commits the current transaction on the current model connection.
Rolls back the current transaction on the current model connection.
Runs the callback inside a transaction and returns the callback result.
Behavior:
- begins and commits a transaction when no transaction is active
- rolls back automatically when the callback throws
- reuses an already-open outer transaction instead of nesting another one
Converts a Unix timestamp or date string into Y-m-d H:i:s.
Invalid date strings are converted as timestamp 0.
Returns a comma-separated placeholder string for IN (...) clauses.
Examples:
[1, 2, 3]->?,?,?[]->NULL
Calls update() when the primary key is non-null; otherwise calls insert().
Primary key values 0 and '0' count as existing primary keys and therefore use the update path.
Inserts the current model as a new row.
Behavior:
- auto-fills the configured created/update timestamp columns when enabled and the fields exist
- runs
validateForSave()andvalidateForInsert() - clears dirty flags on success
- updates the model's primary key from the database when the key is generated by the database
- supports default-values inserts when there are no dirty fields
Set $allowSetPrimaryKey to true to include the current primary key value in the insert.
Updates the current row by primary key.
Behavior:
- auto-fills the configured update timestamp column when enabled and the field exists
- runs
validateForSave()andvalidateForUpdate() - updates only dirty known fields
- returns
falsewhen there are no dirty fields to write - treats zero changed rows as success when the target row still exists
Deletes the current row by primary key. Returns the result of deleteById().
Deletes one row by primary key. Returns true only when one row was removed.
Deletes rows matching a condition fragment. Returns the raw statement.
Pass only the expression that belongs after WHERE.
Returns one model instance for the matching primary key, or null.
Returns the row with the lowest primary key value, or null.
Returns the row with the highest primary key value, or null.
Returns an array of model instances matching the primary key value.
This is intentionally different from getById(), which returns a single instance or null.
Returns the total row count for the model table.
Returns whether the table contains at least one row.
Base helper for conditional reads.
Pass only the fragment that belongs after WHERE.
Returns all matching rows as model instances.
Returns the first matching row as a model instance, or null.
fetchAllWhereOrderedBy(string $orderByField, string $direction = 'ASC', string $SQLfragment = '', array $params = [], ?int $limit = null): array
Returns all matching rows ordered by a real model field.
Constraints:
$orderByFieldmust resolve to a real model field$directionmust beASCorDESC$limit, when provided, must be greater than0
fetchOneWhereOrderedBy(string $orderByField, string $direction = 'ASC', string $SQLfragment = '', array $params = []): ?static
Returns the first matching row using explicit ordering.
pluck(string $fieldname, string $SQLfragment = '', array $params = [], ?string $orderByField = null, string $direction = 'ASC', ?int $limit = null): array
Returns one column from matching rows as a plain array.
Both $fieldname and $orderByField must resolve to real model fields.
Returns the number of rows matching the condition fragment.
Returns whether at least one row matches the condition fragment.
The model supports a dynamic method family through __callStatic().
Preferred forms:
findBy<Field>($match)findOneBy<Field>($match)firstBy<Field>($match)lastBy<Field>($match)countBy<Field>($match)
Examples:
Category::findByName('Fiction');
Category::findOneByUpdatedAt('2026-03-08 12:00:00');
Category::countByName(['Fiction', 'Fantasy']);Rules:
- field names are resolved against real columns
- camelCase field names can map to snake_case columns
- scalar matches become
= ? - array matches become
IN (...) - empty arrays short-circuit without querying the database
Legacy snake_case dynamic methods remain supported temporarily:
find_by_name($match)findOne_by_name($match)first_by_name($match)last_by_name($match)count_by_name($match)
Those methods emit E_USER_DEPRECATED.
Returns one row for a single-column match.
Returns all rows for a single-column match.
Legacy static validation hook. Returns true by default.
Shared instance-level validation hook for both insert and update. By default it calls static::validate().
Insert-specific validation hook. No-op by default.
Update-specific validation hook. No-op by default.
Preferred customisation is to override the instance methods, not the legacy static method.
Enables or disables strict field mode for the current model class.
Returns whether strict field mode is currently enabled.
The API can raise these ORM-specific exceptions:
Freshsauce\Model\Exception\ConfigurationExceptionFreshsauce\Model\Exception\ConnectionExceptionFreshsauce\Model\Exception\InvalidDynamicMethodExceptionFreshsauce\Model\Exception\MissingDataExceptionFreshsauce\Model\Exception\ModelExceptionFreshsauce\Model\Exception\UnknownFieldException
PDO exceptions still bubble up for database-level errors.