FrostMVC\Model
use FrostMVC\Model;
Query builder and base model class for FrostMVC.
Provides a fluent chainable API for building and executing parameterised MySQL queries (SELECT, INSERT, UPDATE, DELETE, JOINs, subqueries, CTEs). Models extend this class and are automatically mapped to a table whose name is derived from the subclass name plus TABLE_PREFIX / TABLE_SUFFIX.
Inline values wrapped in {} braces are treated as raw SQL expressions and are not bound as parameters. Use Model::escape() to produce such values.
| Property | Type | Description |
|---|---|---|
| $require | FrostMVC\Loader |
| ->__construct() | Initialises the model, attaches to the active DB connection, and derives the table name from the subclass name plus TABLE_PREFIX / TABLE_SUFFIX. |
| ->_() | Core method for appending SQL fragments or parameterised expressions. append() is a public alias. |
| ::alias() | Returns an escaped "table AS alias" expression for use in FROM or JOIN clauses. |
| ->all() | Appends ALL or * to the query. When $symbol is true, appends the asterisk wildcard (*). When false (default), appends the SQL ALL keyword (e.g. for UNION ALL). |
| ->and_() | Appends an AND condition to the query. |
| ->append() | Appends raw SQL keywords, operators, or parameterised expressions to the current query. An alias for _(). See _() for the full list of accepted forms. |
| ->append_params_collection() | Merges external parameter names and values into this model's bindings. Existing parameters with the same name are not overwritten. |
| ->as() | Appends an AS alias clause to the current query fragment. |
| ->beginTransaction() | Starts a database transaction on the active DB connection. |
| ->between() | Appends a BETWEEN … AND … clause with both bounds bound as parameters, or as raw expressions when they are Model::escape() values. |
| ->cache() | Enables result caching for the next read(), readRow(), or readScalar() call. |
| ::cast() | Returns a CAST(table.column AS type) SQL expression. |
| ->closeParen() | Appends a closing parenthesis, balancing a preceding openParen() call. |
| ->col() | Appends a column reference to the query. When $tablename is provided the column is qualified as TABLE_PREFIX.$tablename.TABLE_SUFFIX. |
| ->column() | — |
| ->commit() | Commits the current transaction, making all changes permanent. |
| ->date() | Appends a DATE() expression wrapping the given date value. Accepts a Model::escape() expression or a plain date string formatted via Date_Time::MySQLDate(). |
| ->debug() | Returns or prints the prepared SQL string with parameter values substituted in place. Intended for debugging only — do not use the output as an actual query. |
| ->delete() | Builds a DELETE FROM statement for the model's table. Chain where() then execute() to complete and run it. |
| ->equals() | Appends an equality comparison: = :param, or = rawExpr when $value is escaped. |
| ::escape() | Wraps a SQL expression in {} braces so it is treated as a raw expression (not bound as a parameter) when passed to query-builder methods. |
| ->execute() | Prepares and executes the built query, or an ad-hoc query. |
| ->forUpdate() | Appends a FOR UPDATE locking clause to the SELECT query. Locks the selected rows for the duration of the current transaction. |
| ->from() | Appends a FROM clause using a raw SQL expression (e.g. a subquery string from query()). |
| ->get() | Starts a SELECT statement for the model's table. |
| ->get_params_collection() | Returns the internal parameter-name or value array for the current query. |
| ->group() | Appends a GROUP BY clause. |
| ->gt() | Appends a greater-than comparison: > :param. |
| ->gte() | Appends a greater-than-or-equal comparison: >= :param. |
| ->in() | Appends an IN (...) clause. Each array element is bound as a separate parameter. A falsy value (empty array, 0, null) results in IN (0) — always false. |
| ->inner() | Appends an INNER JOIN clause. |
| ->insert() | Builds an INSERT INTO statement for the model's table. Chain execute() to run it. |
| ->is() | Appends an IS comparison: IS NULL, IS TRUE, IS FALSE, etc. Passing null automatically uses "IS NULL". |
| ->isNotNull() | Appends an IS NOT NULL condition. |
| ->isNull() | Appends an IS NULL condition. |
| ->join() | Appends a JOIN clause of the given type. |
| ->left() | Appends a LEFT JOIN clause. |
| ->like() | Appends a LIKE comparison with the given pattern bound as a parameter. |
| ->limit() | Appends a LIMIT clause. |
| ->lt() | Appends a less-than comparison: < :param. |
| ->lte() | Appends a less-than-or-equal comparison: <= :param. |
| ->not() | Appends a NOT or <> (not-equal) condition. |
| ->on() | Appends an operator + column comparison, typically used after join(). |
| ->openParen() | Appends an opening parenthesis, optionally followed by a column reference. Must be balanced with a corresponding closeParen() call. |
| ->or_() | Appends an OR condition to the query. |
| ->order() | Appends an ORDER BY clause. |
| ->params() | Manually binds parameters to named placeholders (:key) in the current SQL string. Useful after composing raw SQL with append() that contains explicit :key tokens. |
| ->query() | Exports this model's current SQL and parameter bindings into a parent model instance, returning the SQL wrapped in parentheses as a subquery string. |
| ->read() | Executes the current SELECT query and returns all matching rows. Results are cached in the session when cache() was chained beforehand. |
| ->readRow() | Executes the current SELECT query and returns the first matching row. Results are cached in the session when cache() was chained beforehand. |
| ->readScalar() | Executes the current SELECT query and returns the value of the first column of the first matching row. |
| ->recursive() | Appends a RECURSIVE CTE clause: RECURSIVE name (col1, col2, …) AS. Chain after with() and before a subquery. |
| ->right() | Appends a RIGHT JOIN clause. |
| ->rollback() | Rolls back the current transaction, discarding all uncommitted changes. |
| ->setConfig() | Replaces the DB connection instance used by this model. Useful for running queries against a secondary database connection. |
| ->setTableName() | Overrides the automatically derived table name. |
| ::tbl() | Returns an escaped column reference qualified with the model's table name. |
| ->union() | Appends a UNION keyword between two SELECT queries. |
| ->update() | Builds an UPDATE SET statement for the model's table. Chain where() then execute() to complete and run it. |
| ->where() | Appends a WHERE clause to the current query. |
| ->with() | Appends a WITH (CTE) clause. |
$model->__construct(&$instance = false)
Initialises the model, attaches to the active DB connection, and derives the table name from the subclass name plus TABLE_PREFIX / TABLE_SUFFIX.
| &$instance | Model|false |
Optional parent model instance whose parameter bindings are shared (used when composing subqueries). Default:false |
$model->_($a, $b = new Nullable(), $c = new Nullable(), $d = new Nullable())
Core method for appending SQL fragments or parameterised expressions. append() is a public alias.
Forms:
_('KEYWORD'): appends the keyword verbatim._('col', $val): appends "col = :param" with $val bound._('col', 'OP', $val): appends "col OP :param" with $val bound._('LOGIC', 'col', 'OP', $val): appends "LOGIC col OP :param".| $a | string |
Keyword, operator, or column. |
| $b | mixed |
Optional value, operator string, or Nullable. Default:new Nullable() |
| $c | mixed |
Optional value (when $b is an operator), or Nullable. Default:new Nullable() |
| $d | mixed |
Optional value (logical-operator form), or Nullable. Default:new Nullable() |
$this
Model::alias($alias, $table = false)
Returns an escaped "table AS alias" expression for use in FROM or JOIN clauses.
| $alias | string |
The alias to assign to the table. |
| $table | string|false |
Explicit table name. Defaults to the model's derived table name. Default:false |
string Model::escape()-wrapped SQL fragment.
$model->all($symbol = false)
Appends ALL or * to the query. When $symbol is true, appends the asterisk wildcard (*). When false (default), appends the SQL ALL keyword (e.g. for UNION ALL).
| $symbol | bool |
True for *, false for ALL. Default:false |
$this
$model->and_($a = new Nullable(), $b = new Nullable(), $c = new Nullable())
Appends an AND condition to the query.
and_(): appends "AND" only.and_('col'): appends "AND col".and_('col', $val): appends "AND col = :param".and_('col', '>=', $val): appends "AND col >= :param".| $a | mixed |
Column name, escaped expression, or Nullable. Default:new Nullable() |
| $b | mixed |
Value or operator, or Nullable. Default:new Nullable() |
| $c | mixed |
Value when $b is an operator, or Nullable. Default:new Nullable() |
$this
$model->append($a, $b = new Nullable(), $c = new Nullable(), $d = new Nullable())
Appends raw SQL keywords, operators, or parameterised expressions to the current query. An alias for _(). See _() for the full list of accepted forms.
| $a | string |
Keyword, operator, or column — appended verbatim. |
| $b | mixed |
Optional value, operator string, or Nullable. Default:new Nullable() |
| $c | mixed |
Optional value (when $b is an operator), or Nullable. Default:new Nullable() |
| $d | mixed |
Optional value (logical-operator form), or Nullable. Default:new Nullable() |
$this
$model->append_params_collection(&$cols, &$vals)
Merges external parameter names and values into this model's bindings. Existing parameters with the same name are not overwritten.
| &$cols | array |
Parameter names to merge. |
| &$vals | array |
Corresponding values to merge. |
$model->as($alias)
Appends an AS alias clause to the current query fragment.
| $alias | string |
The alias name. |
$this
$model->beginTransaction()
Starts a database transaction on the active DB connection.
$model->between($val1, $val2)
Appends a BETWEEN … AND … clause with both bounds bound as parameters, or as raw expressions when they are Model::escape() values.
| $val1 | mixed |
The lower bound. |
| $val2 | mixed |
The upper bound. |
$this
$model->cache($enabled = true)
Enables result caching for the next read(), readRow(), or readScalar() call.
Fresh results (within TABLE_CACHE_EXPIRATION seconds) are served from the session cache. When the cache is stale, the stale data is still returned immediately while a single background process (via register_shutdown_function) re-executes the query and updates the cache — no caller ever waits for a long-running refresh query to finish.
| $enabled | bool |
True to enable caching, false to disable. Default:true |
$this
Model::cast($column, $type, $table = false)
Returns a CAST(table.column AS type) SQL expression.
| $column | string |
Column name or escaped expression. |
| $type | string |
SQL cast type, e.g. 'UNSIGNED', 'CHAR', 'DATE'. |
| $table | string|false |
Explicit table name. Defaults to the model's derived table name. Default:false |
string Raw SQL CAST expression (not wrapped in escape()).
$model->closeParen()
Appends a closing parenthesis, balancing a preceding openParen() call.
$this
$model->col($column, $tablename = new Nullable())
Appends a column reference to the query. When $tablename is provided the column is qualified as TABLE_PREFIX.$tablename.TABLE_SUFFIX.col.
| $column | string |
Column name or escaped expression. |
| $tablename | string |
Optional table name (without prefix/suffix). Default:new Nullable() |
$this
$model->column($cols)
No description yet.
| $cols | mixed |
$model->commit()
Commits the current transaction, making all changes permanent.
$model->date($date)
Appends a DATE() expression wrapping the given date value. Accepts a Model::escape() expression or a plain date string formatted via Date_Time::MySQLDate().
| $date | string |
A Model::escape() expression or a date string. |
$this
$model->debug($return = false)
Returns or prints the prepared SQL string with parameter values substituted in place. Intended for debugging only — do not use the output as an actual query.
| $return | bool |
When true, returns the string instead of printing it. Default:false |
string|void
$model->delete()
Builds a DELETE FROM statement for the model's table. Chain where() then execute() to complete and run it.
$this
$model->equals($value = new Nullable())
Appends an equality comparison: = :param, or = rawExpr when $value is escaped.
| $value | mixed |
The value to compare against, or a Model::escape() expression. Default:new Nullable() |
$this
Model::escape($value)
Wraps a SQL expression in {} braces so it is treated as a raw expression (not bound as a parameter) when passed to query-builder methods.
| $value | string |
The raw SQL expression to mark as escaped. |
string
$model->execute($cmd = false, $vals = false, $read = false, $singleResult = false)
Prepares and executes the built query, or an ad-hoc query.
| $cmd | string|false |
Optional raw SQL to execute directly. Default:false |
| $vals | array|false |
Positional values for $cmd's parameters. Default:false |
| $read | bool |
When true, fetches and returns result rows. Default:false |
| $singleResult | bool |
When true (requires $read), fetches only the first row. Default:false |
array|int|bool INSERT: last insert ID. SELECT ($read=true): row array(s). UPDATE/DELETE: true. Failure: false.
$model->forUpdate()
Appends a FOR UPDATE locking clause to the SELECT query. Locks the selected rows for the duration of the current transaction.
$this
$model->from($query)
Appends a FROM clause using a raw SQL expression (e.g. a subquery string from query()).
| $query | string |
Raw SQL expression, typically produced by query(). |
$this
$model->get($cols = false, $resetQuery = true)
Starts a SELECT statement for the model's table.
$cols accepts several forms:
col| $cols | array|string|false |
Columns to select. Omit to select all columns. Default:false |
| $resetQuery | bool |
When false, appends SELECT instead of replacing the query. Default:true |
$this
$model->get_params_collection($type)
Returns the internal parameter-name or value array for the current query.
| $type | string |
'cols' for parameter names, 'vals' for their values. |
array|void
$model->group($a)
Appends a GROUP BY clause.
| $a | string|array |
Column name/expression, or an associative array of ['modelName' => 'column'] for qualified grouping. |
$this
$model->gt($val)
Appends a greater-than comparison: > :param.
| $val | mixed |
The value to compare against. |
$this
$model->gte($val)
Appends a greater-than-or-equal comparison: >= :param.
| $val | mixed |
The value to compare against. |
$this
$model->in($a)
Appends an IN (...) clause. Each array element is bound as a separate parameter. A falsy value (empty array, 0, null) results in IN (0) — always false.
| $a | array|string |
Array of values, or a raw escaped subquery string. |
$this
$model->inner($a, $columnOn = 'id')
Appends an INNER JOIN clause.
| $a | string|array |
Model name, escaped table expression, or ['alias' => escapedTable]. |
| $columnOn | string |
Column for the ON clause, or escaped ON expression. Defaults to 'id'. Default:'id' |
$this
$model->insert($values)
Builds an INSERT INTO statement for the model's table. Chain execute() to run it.
Keys become column names; values are bound as parameters unless wrapped in {} (raw SQL expressions produced by Model::escape()).
| $values | array |
Associative array of ['column' => value]. |
$this
$model->is($value = '')
Appends an IS comparison: IS NULL, IS TRUE, IS FALSE, etc. Passing null automatically uses "IS NULL".
| $value | mixed |
The comparison value. null becomes the literal NULL. Default:'' |
$this
$model->isNotNull()
Appends an IS NOT NULL condition.
$this
$model->isNull()
Appends an IS NULL condition.
$this
$model->join($a, $columnOn = 'id', $type = '')
Appends a JOIN clause of the given type.
$a accepts:
| $a | string|array |
Model name, alias map, or escaped table expression. |
| $columnOn | string |
Join key column, or escaped ON expression. Defaults to 'id'. Default:'id' |
| $type | string |
JOIN type: 'LEFT', 'RIGHT', 'INNER', or '' for plain JOIN. Default:'' |
$this
$model->left($a, $columnOn = 'id')
Appends a LEFT JOIN clause.
| $a | string|array |
Model name, escaped table expression, or ['alias' => escapedTable]. |
| $columnOn | string |
Column for the ON clause, or escaped ON expression. Defaults to 'id'. Default:'id' |
$this
$model->like($a)
Appends a LIKE comparison with the given pattern bound as a parameter.
| $a | string |
The LIKE pattern, e.g. "%term%". |
$this
$model->limit($a, $b = false)
Appends a LIMIT clause.
| $a | int |
Row count, or offset when $b is also specified. |
| $b | int|false |
Row count when $a is the offset. Default:false |
$this
$model->lt($val)
Appends a less-than comparison: < :param.
| $val | mixed |
The value to compare against. |
$this
$model->lte($val)
Appends a less-than-or-equal comparison: <= :param.
| $val | mixed |
The value to compare against. |
$this
$model->not($a = new Nullable(), $word = false)
Appends a NOT or <> (not-equal) condition.
not(): appends "<>".not(true) or not($val, true): appends "NOT".not($val): appends "<> :param" with $val bound.not(Model::escape('expr')): appends "<> expr" (raw).| $a | mixed |
Value to compare against, Nullable, or true for the word NOT. Default:new Nullable() |
| $word | bool |
When true, uses NOT instead of <>. Default:false |
$this
$model->on($column, $operator = '=')
Appends an operator + column comparison, typically used after join().
| $column | string |
Column name or escaped expression to place on the right side. |
| $operator | string |
The comparison operator. Defaults to '='. Default:'=' |
$this
$model->openParen($column = '')
Appends an opening parenthesis, optionally followed by a column reference. Must be balanced with a corresponding closeParen() call.
| $column | string |
Optional column name or escaped expression appended after (. Default:'' |
$this
$model->or_($a = new Nullable(), $b = new Nullable(), $c = new Nullable())
Appends an OR condition to the query.
or_(): appends "OR" only.or_('col'): appends "OR col".or_('col', $val): appends "OR col = :param".or_('col', '>=', $val): appends "OR col >= :param".| $a | mixed |
Column name, escaped expression, or Nullable. Default:new Nullable() |
| $b | mixed |
Value or operator, or Nullable. Default:new Nullable() |
| $c | mixed |
Value when $b is an operator, or Nullable. Default:new Nullable() |
$this
$model->order($a, $b = new Nullable())
Appends an ORDER BY clause.
| $a | string|array |
Column name, escaped expression, or an associative array of ['escapedCol' => 'ASC'|'DESC'] for multi-column ordering. |
| $b | string |
Sort direction: 'ASC' or 'DESC'. Defaults to 'ASC'. Default:new Nullable() |
$this
$model->params($a, $b = new Nullable())
Manually binds parameters to named placeholders (:key) in the current SQL string. Useful after composing raw SQL with append() that contains explicit :key tokens.
| $a | array|string |
Associative array of ['key' => value], or a single key name. |
| $b | mixed |
Value when $a is a single key name. Default:new Nullable() |
$this
$model->query(&$instance, $isEscaped = false)
Exports this model's current SQL and parameter bindings into a parent model instance, returning the SQL wrapped in parentheses as a subquery string.
| &$instance | Model |
The parent model to merge parameter bindings into. |
| $isEscaped | bool |
When true, wraps the result with Model::escape() so it can be used as a raw expression in the parent query. Default:false |
string The subquery SQL wrapped in parentheses.
$model->read($cmd = false, $vals = false)
Executes the current SELECT query and returns all matching rows. Results are cached in the session when cache() was chained beforehand.
| $cmd | string|false |
Optional raw SQL to run instead of the built query. Default:false |
| $vals | array|false |
Values for $cmd's parameters. Default:false |
array Array of associative row arrays, empty array on no results.
$model->readRow($cmd = false, $vals = false)
Executes the current SELECT query and returns the first matching row. Results are cached in the session when cache() was chained beforehand.
| $cmd | string|false |
Optional raw SQL to run instead of the built query. Default:false |
| $vals | array|false |
Values for $cmd's parameters. Default:false |
array Associative row array, empty array if no row matched.
$model->readScalar($default = false, $cmd = false, $vals = false)
Executes the current SELECT query and returns the value of the first column of the first matching row.
| $default | mixed |
Returned when no row matched or the column value is NULL/false. Default:false |
| $cmd | string|false |
Optional raw SQL to run. Default:false |
| $vals | array|false |
Values for $cmd's parameters. Default:false |
mixed
$model->recursive($name, $a)
Appends a RECURSIVE CTE clause: RECURSIVE name (col1, col2, …) AS. Chain after with() and before a subquery.
| $name | string |
CTE name. |
| $a | array |
Array of column names for the CTE signature. |
$this
$model->right($a, $columnOn = 'id')
Appends a RIGHT JOIN clause.
| $a | string|array |
Model name, escaped table expression, or ['alias' => escapedTable]. |
| $columnOn | string |
Column for the ON clause, or escaped ON expression. Defaults to 'id'. Default:'id' |
$this
$model->rollback()
Rolls back the current transaction, discarding all uncommitted changes.
$model->setConfig($config)
Replaces the DB connection instance used by this model. Useful for running queries against a secondary database connection.
| $config | DB |
$model->setTableName($name)
Overrides the automatically derived table name.
| $name | string |
The full table name, including any prefix/suffix. |
Model::tbl($column = '', $table = false)
Returns an escaped column reference qualified with the model's table name.
| $column | string|array |
Column name, '*', array of column [name => alias], or '' for table only. Default:'' |
| $table | string|false |
Explicit table name. Defaults to the model's derived table name. Default:false |
string Model::escape()-wrapped SQL fragment.
$model->union()
Appends a UNION keyword between two SELECT queries.
$this
$model->update($a, $b = new Nullable())
Builds an UPDATE SET statement for the model's table. Chain where() then execute() to complete and run it.
| $a | array|string |
Associative array of ['column' => value], or a single column name when $b is also provided. |
| $b | mixed |
Value for $a when $a is a column name. Default:new Nullable() |
$this
$model->where($a = false, $b = new Nullable())
Appends a WHERE clause to the current query.
Accepts several forms:
where(['col' => $val, ...]): AND-joined equality conditions.where('col', $val): single equality condition.where(Model::escape('raw SQL')): raw expression appended after WHERE.| $a | array|string|false |
Column map, single column name, or raw escaped expression. Default:false |
| $b | mixed |
Value when $a is a single column name. Default:new Nullable() |
$this
$model->with($name = new Nullable(), $a = new Nullable())
Appends a WITH (CTE) clause.
with(): appends "WITH" only.with('cte_name'): appends "WITH cte_name".with('cte_name', ['col1', 'col2']): appends "WITH cte_name (col1,col2) AS".| $name | string|Nullable |
Optional CTE name. Default:new Nullable() |
| $a | array|string|Nullable |
Optional column list array, or inline expression. Default:new Nullable() |
$this
Generated from core/classes/Model.php (FrostMVC ).