Welcome to FrostSW!

FrostMVC PHP Framework

Documentation   |   Version

Model

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.

Properties

PropertyTypeDescription
$require FrostMVC\Loader

Methods

->__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.col.

->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.

__construct()

$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.

Parameters

&$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".

Parameters

$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()

Returns

$this

alias() static

Model::alias($alias, $table = false)

Returns an escaped "table AS alias" expression for use in FROM or JOIN clauses.

Parameters

$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

Returns

string Model::escape()-wrapped SQL fragment.

all()

$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).

Parameters

$symbol bool

True for *, false for ALL.

Default: false

Returns

$this

and_()

$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".

Parameters

$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()

Returns

$this

append()

$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.

Parameters

$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()

Returns

$this

append_params_collection()

$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.

Parameters

&$cols array

Parameter names to merge.

&$vals array

Corresponding values to merge.

as()

$model->as($alias)

Appends an AS alias clause to the current query fragment.

Parameters

$alias string

The alias name.

Returns

$this

beginTransaction()

$model->beginTransaction()

Starts a database transaction on the active DB connection.

between()

$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.

Parameters

$val1 mixed

The lower bound.

$val2 mixed

The upper bound.

Returns

$this

cache()

$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.

Parameters

$enabled bool

True to enable caching, false to disable.

Default: true

Returns

$this

cast() static

Model::cast($column, $type, $table = false)

Returns a CAST(table.column AS type) SQL expression.

Parameters

$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

Returns

string Raw SQL CAST expression (not wrapped in escape()).

closeParen()

$model->closeParen()

Appends a closing parenthesis, balancing a preceding openParen() call.

Returns

$this

col()

$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.

Parameters

$column string

Column name or escaped expression.

$tablename string

Optional table name (without prefix/suffix).

Default: new Nullable()

Returns

$this

column()

$model->column($cols)

No description yet.

Parameters

$cols mixed

commit()

$model->commit()

Commits the current transaction, making all changes permanent.

date()

$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().

Parameters

$date string

A Model::escape() expression or a date string.

Returns

$this

debug()

$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.

Parameters

$return bool

When true, returns the string instead of printing it.

Default: false

Returns

string|void

delete()

$model->delete()

Builds a DELETE FROM statement for the model's table. Chain where() then execute() to complete and run it.

Returns

$this

equals()

$model->equals($value = new Nullable())

Appends an equality comparison: = :param, or = rawExpr when $value is escaped.

Parameters

$value mixed

The value to compare against, or a Model::escape() expression.

Default: new Nullable()

Returns

$this

escape() static

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.

Parameters

$value string

The raw SQL expression to mark as escaped.

Returns

string

execute()

$model->execute($cmd = false, $vals = false, $read = false, $singleResult = false)

Prepares and executes the built query, or an ad-hoc query.

Parameters

$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

Returns

array|int|bool INSERT: last insert ID. SELECT ($read=true): row array(s). UPDATE/DELETE: true. Failure: false.

forUpdate()

$model->forUpdate()

Appends a FOR UPDATE locking clause to the SELECT query. Locks the selected rows for the duration of the current transaction.

Returns

$this

from()

$model->from($query)

Appends a FROM clause using a raw SQL expression (e.g. a subquery string from query()).

Parameters

$query string

Raw SQL expression, typically produced by query().

Returns

$this

get()

$model->get($cols = false, $resetQuery = true)

Starts a SELECT statement for the model's table.

$cols accepts several forms:

  • false / omitted: SELECT *
  • string column name or escaped expression: SELECT col
  • associative array: ['alias' => 'col'] or ['alias' => ['OtherModel' => 'col']]

Parameters

$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

Returns

$this

get_params_collection()

$model->get_params_collection($type)

Returns the internal parameter-name or value array for the current query.

Parameters

$type string

'cols' for parameter names, 'vals' for their values.

Returns

array|void

group()

$model->group($a)

Appends a GROUP BY clause.

Parameters

$a string|array

Column name/expression, or an associative array of ['modelName' => 'column'] for qualified grouping.

Returns

$this

gt()

$model->gt($val)

Appends a greater-than comparison: > :param.

Parameters

$val mixed

The value to compare against.

Returns

$this

gte()

$model->gte($val)

Appends a greater-than-or-equal comparison: >= :param.

Parameters

$val mixed

The value to compare against.

Returns

$this

in()

$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.

Parameters

$a array|string

Array of values, or a raw escaped subquery string.

Returns

$this

inner()

$model->inner($a, $columnOn = 'id')

Appends an INNER JOIN clause.

Parameters

$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'

Returns

$this

insert()

$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()).

Parameters

$values array

Associative array of ['column' => value].

Returns

$this

is()

$model->is($value = '')

Appends an IS comparison: IS NULL, IS TRUE, IS FALSE, etc. Passing null automatically uses "IS NULL".

Parameters

$value mixed

The comparison value. null becomes the literal NULL.

Default: ''

Returns

$this

isNotNull()

$model->isNotNull()

Appends an IS NOT NULL condition.

Returns

$this

isNull()

$model->isNull()

Appends an IS NULL condition.

Returns

$this

join()

$model->join($a, $columnOn = 'id', $type = '')

Appends a JOIN clause of the given type.

$a accepts:

  • Plain model name string: joins TABLE_PREFIX.$a.TABLE_SUFFIX.
  • ['alias' => escapedTableExpr]: joins the escaped table aliased as TABLE_PREFIX.$alias.TABLE_SUFFIX.
  • Escaped expression: appended verbatim as the joined table.

Parameters

$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: ''

Returns

$this

left()

$model->left($a, $columnOn = 'id')

Appends a LEFT JOIN clause.

Parameters

$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'

Returns

$this

like()

$model->like($a)

Appends a LIKE comparison with the given pattern bound as a parameter.

Parameters

$a string

The LIKE pattern, e.g. "%term%".

Returns

$this

limit()

$model->limit($a, $b = false)

Appends a LIMIT clause.

Parameters

$a int

Row count, or offset when $b is also specified.

$b int|false

Row count when $a is the offset.

Default: false

Returns

$this

lt()

$model->lt($val)

Appends a less-than comparison: < :param.

Parameters

$val mixed

The value to compare against.

Returns

$this

lte()

$model->lte($val)

Appends a less-than-or-equal comparison: <= :param.

Parameters

$val mixed

The value to compare against.

Returns

$this

not()

$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).

Parameters

$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

Returns

$this

on()

$model->on($column, $operator = '=')

Appends an operator + column comparison, typically used after join().

Parameters

$column string

Column name or escaped expression to place on the right side.

$operator string

The comparison operator. Defaults to '='.

Default: '='

Returns

$this

openParen()

$model->openParen($column = '')

Appends an opening parenthesis, optionally followed by a column reference. Must be balanced with a corresponding closeParen() call.

Parameters

$column string

Optional column name or escaped expression appended after (.

Default: ''

Returns

$this

or_()

$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".

Parameters

$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()

Returns

$this

order()

$model->order($a, $b = new Nullable())

Appends an ORDER BY clause.

Parameters

$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()

Returns

$this

params()

$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.

Parameters

$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()

Returns

$this

query()

$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.

Parameters

&$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

Returns

string The subquery SQL wrapped in parentheses.

read()

$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.

Parameters

$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

Returns

array Array of associative row arrays, empty array on no results.

readRow()

$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.

Parameters

$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

Returns

array Associative row array, empty array if no row matched.

readScalar()

$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.

Parameters

$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

Returns

mixed

recursive()

$model->recursive($name, $a)

Appends a RECURSIVE CTE clause: RECURSIVE name (col1, col2, …) AS. Chain after with() and before a subquery.

Parameters

$name string

CTE name.

$a array

Array of column names for the CTE signature.

Returns

$this

rollback()

$model->rollback()

Rolls back the current transaction, discarding all uncommitted changes.

setConfig()

$model->setConfig($config)

Replaces the DB connection instance used by this model. Useful for running queries against a secondary database connection.

Parameters

$config DB

setTableName()

$model->setTableName($name)

Overrides the automatically derived table name.

Parameters

$name string

The full table name, including any prefix/suffix.

tbl() static

Model::tbl($column = '', $table = false)

Returns an escaped column reference qualified with the model's table name.

  • No arguments: returns the escaped table name.
  • '*': returns table.*.
  • Array: returns multiple qualified references, optionally with AS aliases.

Parameters

$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

Returns

string Model::escape()-wrapped SQL fragment.

union()

$model->union()

Appends a UNION keyword between two SELECT queries.

Returns

$this

update()

$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.

Parameters

$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()

Returns

$this

where()

$model->where($a = false, $b = new Nullable())

Appends a WHERE clause to the current query.

Accepts several forms:

  • No arguments: appends "WHERE" only; chain further conditions manually.
  • where(['col' => $val, ...]): AND-joined equality conditions.
  • where('col', $val): single equality condition.
  • where(Model::escape('raw SQL')): raw expression appended after WHERE.

Parameters

$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()

Returns

$this

with()

$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".

Parameters

$name string|Nullable

Optional CTE name.

Default: new Nullable()
$a array|string|Nullable

Optional column list array, or inline expression.

Default: new Nullable()

Returns

$this

Generated from core/classes/Model.php (FrostMVC ).