The Query Builder provides an elegant way of creating SQL statements and clauses on different levels of complexity.
Next, you will find a list of available statements and clauses:
- Statements
- Clauses
SELECT
is used to retrieve rows selected from one or more tables.
Example:
$query = new Greg\Orm\Query\SelectQuery();
$query->from('Table');
echo $query->toString();
// SELECT * FROM `Table`
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Query\SelectQuery($dialect);
Supported clauses:
- From -
FROM
clause; - Join -
JOIN
clause; - Where -
WHERE
clause; - Group By -
GROUP BY
clause; - Having -
HAVING
clause; - Order By -
ORDER BY
clause; - Limit -
LIMIT
clause; - Offset -
OFFSET
clause.
Magic methods:
- __toString
- __clone
Supported methods:
- distinct - The
DISTINCT
is used to return only distinct (different) values; - columnsFrom - Select columns from a table;
- columns - Select columns;
- column - Select column;
- columnConcat - Select concatenated columns;
- columnSelect - Select sub-query column;
- columnRaw - Select raw column;
- count - Select column count;
- max - Select column maximum value;
- min - Select column minimum value;
- avg - Select column average;
- sum - Select column sum;
- hasColumns - Determines if has custom select columns;
- getColumns - Get select columns;
- clearColumns - Clear select columns;
- union - UNION is used to combine the result from multiple SELECT statements into a single result set;
- unionAll - The result includes all matching rows from all the SELECT statements;
- unionRaw - Perform UNION with a raw SQL;
- unionAllRaw - Perform UNION ALL with a raw SQL statement;
- hasUnions - Determines if select has unions;
- getUnions - Get select unions;
- clearUnions - Clear select unions;
- lockForUpdate - Locks the rows and any associated index entries;
- lockInShareMode - Sets a shared mode lock on any rows that are read.
- hasLock - Determines if select has a lock;
- getLock - Get the select lock;
- clearLock - Clear the select lock;
- selectToSql - Get SELECT SQL clause with parameters;
- selectToString - Get SELECT SQL clause;
- toSql - Get SQL statement with parameters;
- toString - Get SQL statement.
The DISTINCT
is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values and sometimes you only want to list the different (distinct) values.
public function distinct(bool $value = true): $this
$value
- true
or false
. Default true
.
Example:
$query->distinct()->from('Table');
echo $query->toString();
// SELECT DISTINCT * FROM `Table`
Select columns from a table.
public function columnsFrom(mixed $table, string $column, string ...$columns): $this
$table
- Table to select from;
$column
- Column from table;
...$columns
- Other columns from table.
Example:
$query
->columnsFrom('Table1 as t1', 'Column1', 'Column2')
->columnsFrom(['t2' => 'Table2'], 'Column1', 'Column2');
echo $query->toString();
// SELECT `t1`.`Column1`, `t1`.`Column2`, `t2`.`Column1`, `t2`.`Column2` FROM `Table1` AS `t1`, `Table2` AS `t2`
Select columns.
public function columns(string $column, string ...$columns): $this
$column
- Column;
...$columns
- Other columns.
Example:
$query->columns('Column1 as c1', 'Column2')->from('Table');
echo $query->toString();
// SELECT `Column1` AS `c1`, `Column2` FROM `Table`
Select column.
public function column(string $column, ?string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->column('Column1 as c1')
->column('Column2', 'c2')
->from('Table');
echo $query->toString();
// SELECT `Column1` AS `c1`, `Column2` AS `c2` FROM `Table`
Select concatenated columns.
public function columnConcat(array $columns, string $delimiter = '', ?string $alias = null): $this
$columns
- Columns to concatenate;
$delimiter
- Delimiter;
$alias
- Columns alias.
Example:
$query
->columnConcat(['Column1', 'Column2'], ", ", "result")
->from('Table');
echo $query->toString();
// SELECT `Column1` + ? + `Column2` AS `result` FROM `Table`
Select sub-query column.
public function columnSelect(\Greg\Orm\Query\SelectQuery $query, ?string $alias = null): $this
$query
- Select query;
$alias
- Query alias.
Example:
$countQuery = new \Greg\Orm\Query\SelectQuery();
$countQuery->count('Column')->from('Table1');
$query
->column('Column')
->columnSelect($countQuery, "count")
->from('Table2');
echo $query->toString();
// SELECT `Column`, (SELECT COUNT(`Column`) FROM `Table1`) AS `count` FROM `Table2`
Select raw column.
public function columnRaw(string $sql, string ...$params): $this
$sql
- SQL statement;
...$params
- Statement parameters.
Example:
$query
->columnRaw('SUM(`Column1` + `Column2`) AS `sum`')
->from('Table');
echo $query->toString();
// SELECT SUM(`Column1` + `Column2`) AS `sum` FROM `Table`
Select column count.
public function count(string $column = '*', string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->count('Column', 'count')
->from('Table');
echo $query->toString();
// SELECT COUNT(`Column`) AS `count` FROM `Table`
Select column maximum value.
public function max(string $column, string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->max('Column', 'max')
->from('Table');
echo $query->toString();
// SELECT MAX(`Column`) AS `max` FROM `Table`
Select column minimum value.
public function min(string $column, string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->min('Column', 'min')
->from('Table');
echo $query->toString();
// SELECT MIN(`Column`) AS `min` FROM `Table`
Select column average.
public function avg(string $column, string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->avg('Column', 'avg')
->from('Table');
echo $query->toString();
// SELECT AVG(`Column`) AS `avg` FROM `Table`
Select column sum.
public function sum(string $column, string $alias = null): $this
$column
- Column;
$alias
- Column alias.
Example:
$query
->sum('Column', 'sum')
->from('Table');
echo $query->toString();
// SELECT SUM(`Column`) AS `sum` FROM `Table`
Determines if has custom select columns.
public function hasColumns(): bool
Example:
$query->hasColumns(); // result: false
$query->column('Column');
$query->hasColumns(); // result: true
Get select columns.
public function getColumns(): array
Example:
$query->columns('Column1', 'Column2 as c2');
$columns = $query->getColumns();
//[
// ['sql' => '`Column1`', 'alias' => null, 'params' => []],
// ['sql' => '`Column2`', 'alias' => 'c2', 'params' => []]
//]
Clear select columns.
public function clearColumns(): $this
Example:
$query->columns('Column1', 'Column2 as c2');
$query->hasColumns(); // result: true
$query->clearColumns();
$query->hasColumns(); // result: false
UNION is used to combine the result from multiple SELECT statements into a single result set.
The UNION operator selects only distinct values by default. To allow duplicate values, use unionAll.
The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)
If the data types of corresponding SELECT columns do not match, the types and lengths of the columns in the UNION result take into account the values retrieved by all of the SELECT statements.
public function union(\Greg\Orm\Query\SelectQuery $query): $this
$query
- Select statement.
Example:
$unionQuery = new \Greg\Orm\Query\SelectQuery();
$unionQuery->from('Table2')->column('Column');
$query
->from('Table1')
->column('Column')
->union($unionQuery);
echo $query->toString();
// (SELECT `Column` FROM `Table1`) UNION (SELECT `Column` FROM `Table2`)
See union for details.
The result includes all matching rows from all the SELECT statements;
public function union(\Greg\Orm\Query\SelectQuery $query): $this
$query
- Select statement.
Example:
$unionQuery = new \Greg\Orm\Query\SelectQuery();
$unionQuery->from('Table2')->column('Column');
$query
->from('Table1')
->column('Column')
->unionAll($unionQuery);
echo $query->toString();
// (SELECT `Column` FROM `Table1`) UNION ALL (SELECT `Column` FROM `Table2`)
See union for details.
public function unionRaw(string $sql, string ...$params): $this
$sql
- Select statement;
...$params
- Statement parameters.
Example:
$query
->from('Table1')
->column('Column')
->unionRaw('SELECT `Column` FROM `Table2`');
echo $query->toString();
// (SELECT `Column` FROM `Table1`) UNION (SELECT `Column` FROM `Table2`)
See unionAll for details.
public function unionAllRaw(string $sql, string ...$params): $this
$sql
- Select statement;
...$params
- Statement parameters.
Example:
$query
->from('Table1')
->column('Column')
->unionAllRaw('SELECT `Column` FROM `Table2`');
echo $query->toString();
// (SELECT `Column` FROM `Table1`) UNION ALL (SELECT `Column` FROM `Table2`)
Determines if select has unions.
public function hasUnions(): bool
Example:
$query->hasUnions(); // result: false
$query->unionRaw('SELECT * FROM `Table`');
$query->hasUnions(); // result: true
Get select unions.
public function getUnions(): array
Example:
$query->unionAllRaw('SELECT * FROM `Table`');
$unions = $query->getUnions();
//Array
//(
// [0] => Array
// (
// [type] => ALL
// [sql] => SELECT * FROM `Table`
// [params] => Array
// (
// )
// )
//)
Clear select unions.
public function clearUnions(): $this
Example:
$query->unionAllRaw('SELECT * FROM `Table`');
$query->hasUnions(); // result: true
$query->clearUnions();
$query->hasUnions(); // result: false
For index records the search encounters, locks the rows and any associated index entries, the same as if you issued an UPDATE statement for those rows. Other transactions are blocked from updating those rows, from doing lockInShareMode, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view.
NOTE: Currently works only for MySQL driver. For others this rule is ignored.
public function lockForUpdate(): $this
Example:
$query->lockForUpdate()->from('Table');
echo $query->toString();
// SQL: SELECT * FROM `Table`
// MySQL: SELECT * FROM `Table` FOR UPDATE
Sets a shared mode lock on any rows that are read. Other sessions can read the rows, but cannot modify them until your transaction commits. If any of these rows were changed by another transaction that has not yet committed, your query waits until that transaction ends and then uses the latest values.
NOTE: Currently works only for MySQL driver. For others this rule is ignored.
public function lockInShareMode(): $this
Example:
$query->lockInShareMode()->from('Table');
echo $query->toString();
// SQL: SELECT * FROM `Table`
// MySQL: SELECT * FROM `Table` FOR SHARE
Determines if select has a lock.
public function hasLock(): bool
Example:
$query->hasLock(); // result: false
$query->lockInShareMode();
$query->hasLock(); // result: true
Get the select lock. Available values:
const LOCK_FOR_UPDATE = 'FOR UPDATE';
const LOCK_IN_SHARE_MORE = 'FOR SHARE';
public function getLock(): array
Example:
$query->lockInShareMode();
$lock = $query->getLock(); // result: self::LOCK_IN_SHARE_MORE
Clear the select lock.
public function clearLock(): $this
Example:
$query->lockInShareMode();
$query->hasLock(); // result: true
$query->clearLock();
$query->hasLock(); // result: false
Get SELECT SQL clause with parameters.
public function selectToSql(): array
Example:
$query->columnRaw('`Column` + ? AS `col`', 'foo')->from('Table');
echo $query->selectToSql();
// ['SELECT `Column` + ? AS `col`', ['foo']]
Get SELECT SQL clause.
public function selectToString(): string
Example:
$query->columnRaw('`Column` + ? AS `col`', 'foo')->from('Table');
echo $query->selectToString();
// SELECT `Column` + ? AS `col`
Get SQL statement with parameters.
public function toSql(): array
Example:
$query->columnRaw('`Column` + ? AS `col`', 'foo')->from('Table');
$sql = $query->toSql();
// ['SELECT `Column` + ? AS `col` FROM `Table`', ['foo']]
Get SQL statement.
public function toString(): string
Example:
$query->columnRaw('`Column` + ? AS `col`', 'foo')->from('Table');
echo $query->toString();
// SELECT `Column` + ? AS `col` FROM `Table`
The UPDATE
statement is used to modify the existing records in a table.
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
Example:
$query = new Greg\Orm\Query\UpdateQuery();
$query->table('Table')->set('Column', 'value');
echo $query->toString();
// UPDATE `Table` SET `Column` = ?
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Query\UpdateQuery($dialect);
Supported clauses:
Magic methods:
- __toString
- __clone
Supported methods:
- table - Update table.
- hasTables - Determines if has custom update tables;
- getTables - Get update tables;
- clearTables - Clear update tables;
- set - Set new column-value;
- setMultiple - Set multiple new column-value;
- setRaw - Set raw SQL;
- increment - Increment a column value;
- decrement - Decrement a column value;
- hasSet - Determines if has SET values;
- getSet - Get defined SET values;
- clearSet - Clear defined SET values;
- updateToSql - Get UPDATE SQL clause with parameters;
- updateToString - Get UPDATE SQL clause;
- setToSql - Get SET SQL clause with parameters;
- setToString - Get SET SQL clause;
- toSql - Get SQL statement with parameters;
- toString - Get SQL statement.
Update table.
public function table($table, ...$tables): $this
$table
- Table name;
...$tables
- Other tables names.
Example:
$query
->table('Table')
->set('Column', 'foo');
echo $query->toString();
// UPDATE `Table` SET `Column` = ?
Determines if has custom update tables.
public function hasTables(): bool
Example:
$query->hasTables(); // result: false
$query->table('Table');
$query->hasTables(); // result: true
Get update tables.
public function getTables(): array
Example:
$query->table('Table1', 'Table2 as t2');
$tables = $query->getTables();
//[
// ['tableKey' => 'Table1', 'table' => '`Table1`', 'alias' => null],
// ['tableKey' => 'Table2', 'table' => '`Table2`', 'alias' => 't2'],
//]
Clear update tables.
public function clearTables(): $this
Example:
$query->table('Table1', 'Table2 as t2');
$query->hasTables(); // result: true
$query->clearTables();
$query->hasTables(); // result: false
Set new column-value.
public function set(string $column, string $value): $this
$column
- Column name;
$value
- Column value.
Example:
$query
->table('Table')
->set('Column', 'foo');
echo $query->toString();
// UPDATE `Table` SET `Column` = ?
Set multiple new column-value.
public function setMultiple(array $columns): $this
$columns
- An array of column-value pairs.
Example:
$query
->table('Table')
->setMultiple([
'Column1' => 'foo',
'Column2' => 'bar',
]);
echo $query->toString();
// UPDATE `Table` SET `Column1` = ?, `Column2` = ?
Set raw SQL.
public function setRaw(string $sql, string ...$params): $this
$sql
- SET SQL statement;
...$params
- Statement parameters.
Example:
$query
->table('Table')
->setRaw('`Column` = ?', 'foo');
echo $query->toString();
// UPDATE `Table` SET `Column` = ?
Increment a column value.
public function increment(string $column, int $step = 1): $this
$column
- Column;
$step
- Increment step.
Example:
$query
->table('Table')
->increment('Column');
echo $query->toString();
// UPDATE `Table` SET `Column` = `Column` + ?
Decrement a column value.
public function decrement(string $column, int $step = 1): $this
$column
- Column;
$step
- Decrement step.
Example:
$query
->table('Table')
->decrement('Column');
echo $query->toString();
// UPDATE `Table` SET `Column` = `Column` - ?
Determines if has SET values.
public function hasSet(): bool
Example:
$query->hasSet(); // result: false
$query->set('Column', 'foo');
$query->hasSet(); // result: true
Get defined SET values.
public function getSet(): array
Example:
$query->set('Column1', 'foo');
$query->set('Column2', 'bar');
$set = $query->getSet();
//[
// ['sql' => '`Column1` = ?', 'params' => ['foo']],
// ['sql' => '`Column2` = ?', 'params' => ['bar']],
//]
Clear defined SET values.
public function clearSet(): $this
Example:
$query->set('Column', 'foo');
$query->hasSet(); // result: true
$query->clearSet();
$query->hasSet(); // result: false
Get UPDATE SQL clause with parameters.
public function updateToSql(): array
Example:
$query->table('Table')->set('Column', 'foo');
echo $query->updateToSql();
// ['UPDATE `Table`', []]
Get UPDATE SQL clause.
public function updateToString(): string
Example:
$query->table('Table')->set('Column', 'foo');
echo $query->setToString();
// UPDATE `Table`
Get SET SQL clause with parameters.
public function setToSql(): array
Example:
$query->table('Table')->set('Column', 'foo');
echo $query->setToSql();
// ['SET `Column` = ?', ['foo']]
Get SET SQL clause.
public function setToString(): string
Example:
$query->table('Table')->set('Column', 'foo');
echo $query->setToString();
// SET `Column` = ?
Get SQL statement with parameters.
public function toSql(): array
Example:
$query->table('Table')->set('Column', 'foo');
$sql = $query->toSql();
// ['UPDATE `Table` SET `Column` = ?', ['foo']]
Get SQL statement.
public function toString(): string
Example:
$query->table('Table')->set('Column', 'foo');
echo $query->toString();
// UPDATE `Table` SET `Column` = ?
The DELETE statement is used to delete records from a table.
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Example:
$query = new Greg\Orm\Query\DeleteQuery();
$query->from('Table')->where('Id', 1);
echo $query->toString();
// DELETE FROM `Table` WHERE `Id` = ?
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Query\DeleteQuery($dialect);
List of supported clauses:
- From -
FROM
clause; - Join -
JOIN
clause; - Where -
WHERE
clause; - Order By -
ORDER BY
clause; - Limit -
LIMIT
clause;
List of magic methods:
List of supported methods:
- rowsFrom - Delete rows from table;
- hasRowsFrom - Determine if has tables from where delete the rows;
- getRowsFrom - Get tables from where delete the rows;
- clearRowsFrom - Clear defined tables where delete the rows;
- deleteToSql - Get DELETE SQL clause with parameters;
- deleteToString - Get DELETE SQL clause;
- toSql - Get SQL statement with parameters;
- toString - Get SQL statement;
Delete rows from table.
public function rowsFrom(string $table, string ...$tables): $this
$table
- Table name;
...$tables
- Other tables names.
Example:
$query
->from('Table1', 'Table2 as t2')
->rowsFrom('t2');
echo $query->toString();
// DELETE `t2` FROM `Table1`, `Table2` AS `t2`
Determine if has tables from where delete the rows.
public function hasRowsFrom(): bool
Example:
$query->hasRowsFrom(); // result: false
$query->rowsFrom('Table');
$query->hasRowsFrom(); // result: true
Get tables from where delete the rows.
public function getRowsFrom(): array
Example:
$query->rowsFrom('Table');
$rowsFrom = $query->getRowsFrom(); // result: [`Table`]
Clear defined tables where delete the rows.
public function clearRowsFrom(): $this
Example:
$query->rowsFrom('Table');
$query->hasRowsFrom(); // result: true
$query->clearRowsFrom();
$query->hasRowsFrom(); // result: false
Get DELETE SQL clause with parameters.
public function deleteToSql(): array
Example:
$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');
echo $query->deleteToSql();
// ['DELETE `t2`', []]
Get DELETE SQL clause.
public function deleteToString(): string
Example:
$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');
echo $query->deleteToString();
// DELETE `t2`
Get SQL statement with parameters.
public function toSql(): array
Example:
$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');
$sql = $query->toSql();
// ['DELETE `t2` FROM `Table1`, `Table2` AS `t2`', []]
Get SQL statement.
public function toString(): string
Example:
$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');
echo $query->toString();
// DELETE `t2` FROM `Table1`, `Table2` AS `t2`
The INSERT INTO statement is used to add new records to a MySQL table.
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
Example:
$query = new Greg\Orm\Query\InsertQuery();
$query->into('Table')->data(['Column' => 'value']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Query\InsertQuery($dialect);
List of magic methods:
List of supported methods:
- into - Insert into table;
- hasInto - Determine if has insert into table;
- getInto - Get insert into table;
- clearInto - Clear insert into table;
- columns - Insert into columns;
- hasColumns - Determine if has insert into columns;
- getColumns - Get insert into columns;
- clearColumns - Clear insert into columns;
- values - Insert columns values;
- hasValues - Determine if has insert values;
- getValues - Get insert values;
- clearValues - Clear insert values;
- data - Insert column-value pairs;
- clearData - Clear insert column-value pairs;
- select - Insert select;
- selectRaw - Insert raw select;
- hasSelect - Determine if has insert select;
- getSelect - Get insert select;
- clearSelect - Clear insert select;
- toSql - Get SQL statement with parameters;
- toString - Get SQL statement;
Insert into table.
public function into($table): $this
$table
- Table name.
Example:
$query
->into('Table')
->data(['Column' => 'values']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
Determine if has insert into table.
public function hasInto(): bool
Example:
$query->hasInto(); // result: false
$query->into('Table');
$query->hasInto(); // result: true
Get insert into table.
public function getInto(): array
Example:
$query->into('Table');
$into = $query->getInto(); // result: `Table`
Clear insert into table.
public function clearInto(): $this
Example:
$query->into('Table');
$query->hasInto(); // result: true
$query->clearInto();
$query->hasInto(); // result: false
Insert into columns.
public function columns(array $columns): $this
$columns
- Columns names.
Example:
$query
->into('Table')
->columns(['Column'])
->values(['value']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
Determine if has insert into columns.
public function hasColumns(): bool
Example:
$query->hasColumns(); // result: false
$query->columns(['Column']);
$query->hasColumns(); // result: true
Get insert into columns.
public function getColumns(): array
Example:
$query->columns(['Column1', 'Column2']);
$columns = $query->getColumns(); // result: ['`Column1`', '`Column2`']
Clear insert into columns.
public function clearColumns(): $this
Example:
$query->columns(['Column']);
$query->hasColumns(); // result: true
$query->clearColumns();
$query->hasColumns(); // result: false
Insert values.
public function values(array $values): $this
$values
- Values.
Example:
$query
->into('Table')
->columns(['Column'])
->values(['value']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
Determine if has insert values.
public function hasValues(): bool
Example:
$query->hasValues(); // result: false
$query->values(['value']);
$query->hasValues(); // result: true
Get insert values.
public function getValues(): array
Example:
$query->values(['value1', 'value2']);
$values = $query->getValues(); // result: ['value1', 'value2']
Clear insert values.
public function clearValues(): $this
Example:
$query->values(['value']);
$query->hasValues(); // result: true
$query->clearValues();
$query->hasValues(); // result: false
Insert column-value pairs.
public function data(array $data): $this
$data
- Column-value pairs.
Example:
$query
->into('Table')
->data(['Column' => 'value']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
Clear insert column-value pairs.
public function clearData(): $this
Example:
$query->data(['Column' => 'value']);
$query->hasColumns(); // result: true
$query->hasValues(); // result: true
$query->clearData();
$query->hasColumns(); // result: false
$query->hasValues(); // result: false
Insert select.
public function select(\Greg\Orm\Query\SelectQuery $query): $this
$query
- Select query.
Example:
$selectQuery = new \Greg\Orm\Query\SelectQuery($query->dialect());
$selectQuery->columnsFrom('Table2', 'Column');
$query
->into('Table1')
->columns(['Column'])
->select($selectQuery);
echo $query->toString();
// INSERT INTO `Table` (`Column`) Select `Column` from `Table2`
Insert raw select.
public function selectRaw(string $sql): $this
$sql
- Select raw SQL.
Example:
$query
->into('Table1')
->columns(['Column'])
->select('Select `Column` from `Table2`');
echo $query->toString();
// INSERT INTO `Table` (`Column`) Select `Column` from `Table2`
Determine if has insert select.
public function hasSelect(): bool
Example:
$query->hasSelect(); // result: false
$query->selectRaw('Select `Column` from `Table2`');
$query->hasSelect(); // result: true
Get insert select.
public function getSelect(): array
Example:
$query->selectRaw('Select `Column` from `Table2`');
$sql = $query->getSelect(); // result: Select `Column` from `Table2`
Clear insert select.
public function clearSelect(): $this
Example:
$query->selectRaw('Select `Column` from `Table2`');
$query->hasSelect(); // result: true
$query->clearSelect();
$query->hasSelect(); // result: false
Get SQL statement with parameters.
public function toSql(): array
Example:
$query->into('Table')->data(['Column' => 'value']);
$sql = $query->toSql();
// ['INSERT INTO `Table` (`Column`) VALUES (?)', ['value']]
Get SQL statement.
public function toString(): string
Example:
$query->into('Table')->data(['Column' => 'value']);
echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)
The FROM table_references
clause indicates the table or tables from which to retrieve rows.
If you name more than one table, you are performing a join.
For information on join syntax, see Join Clause.
For each table specified, you can optionally specify an alias.
Example:
$query = new Greg\Orm\Clause\FromClause();
$query->from('Table1', 'Table2 as t2');
echo $query->toString();
// FROM `Table1`, `Table2` AS `t2`
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Clause\FromClause($dialect);
List of magic methods:
List of supported methods:
- from - Define tables;
- fromRaw - Define raw tables;
- fromLogic - Define custom tables logic;
- hasFrom - Determine if has tables;
- getFrom - Get tables;
- clearFrom - Clear tables;
- fromToSql - Get FROM SQL clause with parameters;
- fromToString - Get FROM SQL clause;
- toSql - Get SQL clause with parameters;
- toString - Get SQL clause.
Define tables.
public function from(mixed $table, mixed ...$tables): $this
$table
- Table;
...$tables
- Tables.
Example:
$query->from('Table1', 'Table2 as t2');
echo $query->toString();
// FROM `Table1`, `Table2` AS `t2`
Define raw tables.
public function fromRaw(?string $alias, string $sql, string ...$params): $this
$alias
- Table alias;
$sql
- Table raw SQL;
$params
- Table parameters.
Example:
$query->fromRaw('t', 'SELECT * FROM `Table` WHERE Column = ?', 'value');
echo $query->toString();
// FROM (SELECT * FROM `Table` WHERE Column = ?) AS `t`
Define custom tables logic.
Note: Use this method only if you know what you are doing!
public function fromLogic(?string $tableKey, $table, ?string $alias, array $params = []): $this
$tableKey
- Table key, used with joins;
$table
- The table;
$alias
- Table alias;
$params
- Table parameters.
Example:
$query->fromLogic('table1', '`Table1`', '`t1`');
echo $query->toString();
// FROM `Table1` AS `t1`
$join = new Greg\Orm\Clause\JoinClause($query->dialect());
$join->innerTo('table1', 'Table2 as t2', '!t1.Id = !t2.Table1Id');
echo $query->toString($join);
// FROM `Table1` AS t1 INNER JOIN `Table2` AS `t2` ON `t1`.`Id` = `t2`.`Table1Id`
Determine if has from tables.
public function hasFrom(): bool
Example:
$query->hasFrom(); // result: false
$query->from('Table');
$query->hasFrom(); // result: true
Get from tables.
public function getFrom(): array
Example:
$query->from('Table');
$sql = $query->getFrom();
//Array
//(
// [Table] => Array
// (
// [tableKey] => Table
// [table] => `Table`
// [alias] =>
// [params] => Array
// (
// )
// )
//)
Clear from tables.
public function clearFrom(): $this
Example:
$query->from('Table');
$query->hasFrom(); // result: true
$query->clearFrom();
$query->hasFrom(); // result: false
Get FROM SQL clause with parameters.
public function fromToSql(?JoinClauseStrategy $join = null, bool $useClause = true): array
Example:
$query->from('Table');
$sql = $query->toSql();
// ['FROM `Table`', []]
Get FROM SQL clause.
public function fromToString(?JoinClauseStrategy $join = null, bool $useClause = true): string
Example:
$query->from('Table');
echo $query->toString();
// FROM `Table`
Get SQL clause with parameters.
public function toSql(?JoinClauseStrategy $join = null, bool $useClause = true): array
Example:
$query->from('Table');
$sql = $query->toSql();
// ['FROM `Table`', []]
Get SQL clause.
public function toString(?JoinClauseStrategy $join = null, bool $useClause = true): string
Example:
$query->from('Table');
echo $query->toString();
// FROM `Table`
A JOIN
clause is used to combine rows from two or more tables, based on a related column between them.
Example:
$query = new Greg\Orm\Clause\JoinClause();
$query->inner('Table');
echo $query->toString();
// INNER JOIN `Table`
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Clause\JoinClause($dialect);
List of magic methods:
List of supported methods:
- left - Left join;
- leftOn - Left join with conditions;
- right - Right join;
- rightOn - Right join with conditions;
- inner - Inner join;
- innerOn - Inner join with conditions;
- cross - Cross join;
- leftTo - Left join to a specific FROM table;
- leftToOn - Left join to a specific FROM table with conditions;
- rightTo - Right join to a specific FROM table;
- rightToOn - Right join to a specific FROM table with conditions;
- innerTo - Inner join to a specific FROM table;
- innerToOn - Inner join to a specific FROM table with conditions;
- crossTo - Cross join to a specific FROM table;
- joinLogic - Define custom join logic;
- hasJoin - Determine if has joins;
- getJoin - Get joins;
- clearJoin - Clear joins;
- joinToSql - Get JOIN SQL clause with parameters;
- joinToString - Get JOIN SQL clause;
- toSql - Get SQL clause with parameters;
- toString - Get SQL clause.
Left join.
Return all records from the left table, and the matched records from the right table.
public function left($table, string $on = null, string ...$params): $this
Left join with conditions.
Return all records from the left table, and the matched records from the right table.
public function leftOn($table, $on): $this
Right join.
Return all records from the right table, and the matched records from the left table.
public function right($table, string $on = null, string ...$params): $this
Right join with conditions.
Return all records from the right table, and the matched records from the left table.
public function rightOn($table, $on): $this
Inner join.
Returns records that have matching values in both tables.
public function inner($table, string $on = null, string ...$params): $this
Inner join with conditions.
Returns records that have matching values in both tables.
public function innerOn($table, $on): $this
Cross join.
Return all records when there is a match in either left or right table.
public function cross($table): $this
Left join to a specific FROM table.
Return all records from the left table, and the matched records from the right table.
public function leftTo($source, $table, string $on = null, string ...$params): $this
Left join to a specific FROM table with conditions.
Return all records from the left table, and the matched records from the right table.
public function leftToOn($source, $table, $on): $this
Right join to a specific FROM table.
Return all records from the right table, and the matched records from the left table.
public function rightTo($source, $table, string $on = null, string ...$params): $this
Right join to a specific FROM table with conditions.
Return all records from the right table, and the matched records from the left table.
public function rightToOn($soruce, $table, $on): $this
Inner join to a specific FROM table.
Returns records that have matching values in both tables.
public function innerTo($source, $table, string $on = null, string ...$params): $this
Inner join to a specific FROM table with conditions.
Returns records that have matching values in both tables.
public function innerToOn($source, $table, $on): $this
Cross join to a specific FROM table.
Return all records when there is a match in either left or right table.
public function crossTo($source, $table): $this
Define custom join logic.
Note: Use this method only if you know what you are doing!
public function joinLogic(string $tableKey, string $type, ?string $source, $table, ?string $alias, $on = null, array $params = []): $this
Determine if has joins.
public function hasJoin(): bool
Example:
$query->hasJoin(); // result: false
$query->inner('Table');
$query->hasJoin(); // result: true
Get joins.
public function getJoin(): array
Example:
$query->inner('Table');
$sql = $query->getJoin();
//Array
//(
// [Table] => Array
// (
// [type] => INNER
// [source] =>
// [table] => `Table`
// [alias] =>
// [on] =>
// [params] => Array
// (
// )
// )
//)
Clear joins.
public function clearJoin(): $this
Example:
$query->inner('Table');
$query->hasJoin(); // result: true
$query->clearJoin();
$query->hasJoin(); // result: false
Get JOIN SQL clause with parameters.
public function joinToSql(string $source = null): array
Example:
$query->inner('Table');
$sql = $query->toSql();
// ['INNER JOIN `Table`', []]
Get JOIN SQL clause.
public function joinToString(string $source = null): string
Example:
$query->inner('Table');
echo $query->toString();
// INNER JOIN `Table`
Get SQL clause with parameters.
public function toSql(string $source = null): array
Example:
$query->inner('Table');
$sql = $query->toSql();
// ['INNER JOIN `Table`', []]
Get SQL clause.
public function toString(string $source = null): string
Example:
$query->inner('Table');
echo $query->toString();
// INNER JOIN `Table`
The WHERE
clause is used to filter records.
The WHERE
clause is used to extract only those records that fulfill a specified condition.
Example:
$query = new Greg\Orm\Clause\WhereClause();
$query->where('Column', 'value');
echo $query->toString();
// WHERE `Column` = ?
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Clause\WhereClause($dialect);
List of magic methods:
List of supported methods:
- where - Filter records with AND condition;
- orWhere - Filter records with OR condition;
- whereMultiple - Filter records by column-value with AND condition;
- orWhereMultiple - Filter records by column-value with OR condition;
- whereDate - Filter records by date with AND condition;
- orWhereDate - Filter records by date with OR condition;
- whereTime - Filter records by time with AND condition;
- orWhereTime - Filter records by time with OR condition;
- whereYear - Filter records by year with AND condition;
- orWhereYear - Filter records by year with OR condition;
- whereMonth - Filter records by month with AND condition;
- orWhereMonth - Filter records by month with OR condition;
- whereDay - Filter records by day with AND condition;
- orWhereDay - Filter records by day with OR condition;
- whereRelation - Filter records by column relation with AND condition;
- orWhereRelation - Filter records by column relation with OR condition;
- whereRelations - Filter records by column-column relations with AND condition;
- orWhereRelations - Filter records by column-column relations with OR condition;
- whereIs - Filter records by TRUE column with AND condition;
- orWhereIs - Filter records by TRUE column with OR condition;
- whereIsNot - Filter records by FALSE column with AND condition;
- orWhereIsNot - Filter records by FALSE column with OR condition;
- whereIsNull - Filter records by NULL column with AND condition;
- orWhereIsNull - Filter records by NULL column with OR condition;
- whereIsNotNull - Filter records by NOT NULL column with AND condition;
- orWhereIsNotNull - Filter records by NOT NULL column with OR condition;
- whereBetween - Filter records by column between values with AND condition;
- orWhereBetween - Filter records by column between values with OR condition;
- whereNotBetween - Filter records by column not between values with AND condition;
- orWhereNotBetween - Filter records by column not between values with OR condition;
- whereConditions - Filter records by conditions with AND condition;
- orWhereConditions - Filter records by conditions with OR condition;
- whereRaw - Filter records by raw SQL with AND condition;
- orWhereRaw - Filter records by raw SQL with OR condition;
- whereLogic - Define custom where logic;
- hasWhere - Determine if has where conditions;
- getWhere - Get where conditions;
- clearWhere - Clear where conditions;
- whereExists - Filter records by SELECT if exists;
- whereNotExists - Filter records by SELECT statement if not exists;
- whereExistsRaw - Filter records by raw SELECT statement if exists;
- whereNotExistsRaw - Filter records by raw SELECT statement if not exists;
- hasExists - Determine if has exists SELECT statement;
- getExists - Get exists SELECT statement;
- clearExists - Clear exists SELECT statement;
- whereToSql - Get WHERE SQL clause with parameters;
- whereToString - Get WHERE SQL clause;
- toSql - Get SQL clause with parameters;
- toString - Get SQL clause;
Filter records with AND condition.
public function where(string|array $column, string $operator, string|array $value = null): $this
Filter records with OR condition.
public function orWhere(string|array $column, string $operator, string|array $value = null): $this
Filter records by column-value with AND condition.
public function whereMultiple(array $columns): $this
Filter records by column-value with OR condition.
public function orWhereMultiple(array $columns): $this
Filter records by date with AND condition.
public function whereDate(string|array $column, string $operator, string|array $value = null): $this
Filter records by date with OR condition;
public function orWhereDate(string|array $column, string $operator, string|array $value = null): $this
Filter records by time with AND condition.
public function whereTime(string|array $column, string $operator, string|array $value = null): $this
Filter records by time with OR condition;
public function orWhereTime(string|array $column, string $operator, string|array $value = null): $this
Filter records by year with AND condition.
public function whereYear(string|array $column, string $operator, string|array $value = null): $this
Filter records by year with OR condition;
public function orWhereYear(string|array $column, string $operator, string|array $value = null): $this
Filter records by month with AND condition.
public function whereMonth(string|array $column, string $operator, string|array $value = null): $this
Filter records by month with OR condition;
public function orWhereMonth(string|array $column, string $operator, string|array $value = null): $this
Filter records by day with AND condition.
public function whereDay(string|array $column, string $operator, string|array $value = null): $this
Filter records by day with OR condition;
public function orWhereDay(string|array $column, string $operator, string|array $value = null): $this
Filter records by column relation with AND condition.
public function whereRelation(string|array $column1, string $operator, string|array $column2 = null): $this
Filter records by column relation with OR condition.
public function orWhereRelation(string|array $column1, string $operator, string|array $column2 = null): $this
Filter records by column-column relations with AND condition.
public function whereRelations(array $relations): $this
Filter records by column-column relations with OR condition.
public function orWhereRelations(array $relations): $this
Filter records by TRUE column with AND condition.
public function whereIs(string $column): $this
Filter records by TRUE column with OR condition.
public function orWhereIs(string $column): $this
Filter records by FALSE column with AND condition.
public function whereIsNotNull(string $column): $this
Filter records by FALSE column with OR condition.
public function orWhereIsNotNull(string $column): $this
Filter records by NULL column with AND condition.
public function whereIsNull(string $column): $this
Filter records by NULL column with OR condition.
public function orWhereIsNull(string $column): $this
Filter records by NOT NULL column with AND condition.
public function whereIsNotNull(string $column): $this
Filter records by NOT NULL column with OR condition.
public function orWhereIsNotNull(string $column): $this
Filter records by column between values with AND condition.
public function whereBetween(string $column, int $min, int $max): $this
Filter records by column between values with OR condition.
public function orWhereBetween(string $column, int $min, int $max): $this
Filter records by column not between values with AND condition.
public function whereNotBetween(string $column, int $min, int $max): $this
Filter records by column not between values with OR condition.
public function orWhereNotBetween(string $column, int $min, int $max): $this
Filter records by conditions with AND condition.
public function whereConditions(callable|Conditions|WhereClauseStrategy|HavingClauseStrategy $conditions): $this
Filter records by conditions with OR condition.
public function orWhereConditions(callable|Conditions|WhereClauseStrategy|HavingClauseStrategy $conditions): $this
Filter records by raw SQL with AND condition.
public function whereRaw(string $sql, string ...$params): $this
Filter records by raw SQL with OR condition.
public function orWhereRaw(string $sql, string ...$params): $this
Define custom where logic.
Note: Use this method only if you know what you are doing!
public function whereLogic(string $logic, $sql, array $params = []): $this
Determine if has where conditions.
public function hasWhere(): bool
Example:
$query->hasWhere(); // result: false
$query->where('Column', 'value');
$query->hasWhere(); // result: true
Get where conditions.
public function getWhere(): array
Clear where conditions.
public function clearWhere(): $this
Example:
$query->where('Column', 'value');
$query->hasWhere(); // result: true
$query->clearWhere();
$query->hasWhere(); // result: false
Filter records by SELECT if exists.
public function whereExists(SelectQuery $sql): $this
Filter records by SELECT statement if not exists.
public function whereNotExists(SelectQuery $sql): $this
Filter records by raw SELECT statement if exists.
public function whereExistsRaw(string $sql, string ...$params): $this
Filter records by raw SELECT statement if not exists.
public function whereNotExistsRaw(string $sql, string ...$params): $this
Determine if has exists SELECT statement.
public function hasExists(): bool
Get exists SELECT statement.
public function getExists(): array
Clear exists SELECT statement.
public function clearExists(): $this
Get WHERE SQL clause with parameters.
public function whereToSql(bool $useClause = true): array
Get WHERE SQL clause.
public function whereToString(bool $useClause = true): string
Get SQL clause with parameters.
public function toSql(bool $useClause = true): array
Get SQL clause.
public function toString(bool $useClause = true): string
The GROUP BY
statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG)
to group the result-set by one or more columns.
Example:
$query = new Greg\Orm\Clause\GroupByClause();
$query->groupBy('Column');
echo $query->toString();
// GROUP BY `Column`
Optionally, you can define a SQL dialect for your query. By default it will use base SQL syntax.
$dialect = new \Greg\Orm\Dialect\MysqlDialect();
$query = new Greg\Orm\Clause\GroupByClause($dialect);
List of magic methods:
List of supported methods:
- groupBy - Group by columns;
- groupByRaw - Group by raw columns;
- groupByLogic - Define custom group by logic;
- hasGroupBy - Determine if has group by columns;
- getGroupBy - Get group by columns;
- clearGroupBy - Clear group by columns;
- groupByToSql - Get GROUP BY SQL clause with parameters;
- groupByToString - Get GROUP BY SQL clause;
- toSql - Get SQL clause with parameters;
- toString - Get SQL clause.
Group by columns.
public function groupBy(string $column): $this
Group by raw columns.
public function groupByRaw(string $sql, string ...$params): $this
Define custom group by logic.
public function groupByLogic(string $sql, array $params = []): $this
Determine if has group by columns.
public function hasGroupBy(): bool
Get group by columns.
public function getGroupBy(): array
Clear group by columns.
public function clearGroupBy(): $this
Get GROUP BY SQL clause with parameters.
public function groupByToSql(bool $useClause = true): array
Get GROUP BY SQL clause.
public function groupByToString(bool $useClause = true): string
Get SQL clause with parameters.
public function toSql(bool $useClause = true): array
Get SQL clause.
public function toString(bool $useClause = true): string
HAVING
clause.
List of magic methods:
List of supported methods:
- having
- orHaving
- havingMultiple
- orHavingMultiple
- havingDate
- orHavingDate
- havingTime
- orHavingTime
- havingYear
- orHavingYear
- havingMonth
- orHavingMonth
- havingDay
- orHavingDay
- havingRelation
- orHavingRelation
- havingRelations
- orHavingRelations
- havingIs
- orHavingIs
- havingIsNot
- orHavingIsNot
- havingIsNull
- orHavingIsNull
- havingIsNotNull
- orHavingIsNotNull
- havingBetween
- orHavingBetween
- havingNotBetween
- orHavingNotBetween
- havingGroup
- orHavingGroup
- havingConditions
- orHavingConditions
- havingStrategy
- orHavingStrategy
- havingRaw
- orHavingRaw
- havingLogic
- hasHaving
- getHaving
- clearHaving
- havingToSql
- havingToString
- toSql
- toString
ORDER BY
clause.
List of magic methods:
List of supported methods:
- orderBy
- orderAsc
- orderDesc
- orderByRaw
- orderByLogic
- hasOrderBy
- getOrderBy
- clearOrderBy
- orderByToSql
- orderByToString
- toSql
- toString
LIMIT
clause.
List of supported methods:
OFFSET
clause.
List of supported methods:
Conditions.
List of magic methods:
List of supported methods:
- column
- orColumn
- columns
- orColumns
- date
- orDate
- time
- orTime
- year
- orYear
- month
- orMonth
- day
- orDay
- relation
- orRelation
- relations
- orRelations
- is
- orIs
- isNot
- orIsNot
- isNull
- orIsNull
- isNotNull
- orIsNotNull
- between
- orBetween
- notBetween
- orNotBetween
- conditions
- orConditions
- raw
- orRaw
- logic
- has
- get
- clear
- toSql
- toString