Skip to content

Latest commit

 

History

History
3211 lines (2157 loc) · 60.6 KB

QueryBuilder.md

File metadata and controls

3211 lines (2157 loc) · 60.6 KB

Query Builder

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
    • Select - The SELECT statement is used to select data from a database;
    • Update - The UPDATE statement is used to modify the existing records in a table;
    • Delete - The DELETE statement is used to delete existing records in a table;
    • Insert - The INSERT statement is used to insert new records in a table.
  • Clauses

Select Statement

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:

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.

distinct

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`

columnsFrom

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`

columns

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`

column

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`

columnConcat

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`

columnSelect

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`

columnRaw

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`

count

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`

max

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`

min

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`

avg

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`

sum

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`

hasColumns

Determines if has custom select columns.

public function hasColumns(): bool

Example:

$query->hasColumns(); // result: false

$query->column('Column');

$query->hasColumns(); // result: true

getColumns

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' => []]
//]

clearColumns

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

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`)

unionAll

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`)

unionRaw

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`)

unionAllRaw

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`)

hasUnions

Determines if select has unions.

public function hasUnions(): bool

Example:

$query->hasUnions(); // result: false

$query->unionRaw('SELECT * FROM `Table`');

$query->hasUnions(); // result: true

getUnions

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

clearUnions

Clear select unions.

public function clearUnions(): $this

Example:

$query->unionAllRaw('SELECT * FROM `Table`');

$query->hasUnions(); // result: true

$query->clearUnions();

$query->hasUnions(); // result: false

lockForUpdate

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

lockInShareMode

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

hasLock

Determines if select has a lock.

public function hasLock(): bool

Example:

$query->hasLock(); // result: false

$query->lockInShareMode();

$query->hasLock(); // result: true

getLock

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

clearLock

Clear the select lock.

public function clearLock(): $this

Example:

$query->lockInShareMode();

$query->hasLock(); // result: true

$query->clearLock();

$query->hasLock(); // result: false

selectToSql

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

selectToString

Get SELECT SQL clause.

public function selectToString(): string

Example:

$query->columnRaw('`Column` + ? AS `col`', 'foo')->from('Table');

echo $query->selectToString();
// SELECT `Column` + ? AS `col`

toSql SELECT statement

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

toString SELECT statement

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`

Update Statement

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.

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` = ?

hasTables

Determines if has custom update tables.

public function hasTables(): bool

Example:

$query->hasTables(); // result: false

$query->table('Table');

$query->hasTables(); // result: true

getTables

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'],
//]

clearTables

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

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` = ?

setMultiple

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` = ?

setRaw

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

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

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` - ?

hasSet

Determines if has SET values.

public function hasSet(): bool

Example:

$query->hasSet(); // result: false

$query->set('Column', 'foo');

$query->hasSet(); // result: true

getSet

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']],
//]

clearSet

Clear defined SET values.

public function clearSet(): $this

Example:

$query->set('Column', 'foo');

$query->hasSet(); // result: true

$query->clearSet();

$query->hasSet(); // result: false

updateToSql

Get UPDATE SQL clause with parameters.

public function updateToSql(): array

Example:

$query->table('Table')->set('Column', 'foo');

echo $query->updateToSql();
// ['UPDATE `Table`', []]

updateToString

Get UPDATE SQL clause.

public function updateToString(): string

Example:

$query->table('Table')->set('Column', 'foo');

echo $query->setToString();
// UPDATE `Table`

setToSql

Get SET SQL clause with parameters.

public function setToSql(): array

Example:

$query->table('Table')->set('Column', 'foo');

echo $query->setToSql();
// ['SET `Column` = ?', ['foo']]

setToString

Get SET SQL clause.

public function setToString(): string

Example:

$query->table('Table')->set('Column', 'foo');

echo $query->setToString();
// SET `Column` = ?

toSql UPDATE statement

Get SQL statement with parameters.

public function toSql(): array

Example:

$query->table('Table')->set('Column', 'foo');

$sql = $query->toSql();
// ['UPDATE `Table` SET `Column` = ?', ['foo']]

toString UPDATE statement

Get SQL statement.

public function toString(): string

Example:

$query->table('Table')->set('Column', 'foo');

echo $query->toString();
// UPDATE `Table` SET `Column` = ?

Delete Statement

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:

List of magic methods:

List of supported methods:

rowsFrom

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`

hasRowsFrom

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

getRowsFrom

Get tables from where delete the rows.

public function getRowsFrom(): array

Example:

$query->rowsFrom('Table');

$rowsFrom = $query->getRowsFrom(); // result: [`Table`]

clearRowsFrom

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

deleteToSql

Get DELETE SQL clause with parameters.

public function deleteToSql(): array

Example:

$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');

echo $query->deleteToSql();
// ['DELETE `t2`', []]

deleteToString

Get DELETE SQL clause.

public function deleteToString(): string

Example:

$query->from('Table1', 'Table2 as t2')->rowsFrom('t2');

echo $query->deleteToString();
// DELETE `t2`

toSql DELETE statement

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`', []]

toString DELETE statement

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`

Insert Statement

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.

public function into($table): $this

$table - Table name.

Example:

$query
    ->into('Table')
    ->data(['Column' => 'values']);

echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)

hasInto

Determine if has insert into table.

public function hasInto(): bool

Example:

$query->hasInto(); // result: false

$query->into('Table');

$query->hasInto(); // result: true

getInto

Get insert into table.

public function getInto(): array

Example:

$query->into('Table');

$into = $query->getInto(); // result: `Table`

clearInto

Clear insert into table.

public function clearInto(): $this

Example:

$query->into('Table');

$query->hasInto(); // result: true

$query->clearInto();

$query->hasInto(); // result: false

columns

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

hasColumns

Determine if has insert into columns.

public function hasColumns(): bool

Example:

$query->hasColumns(); // result: false

$query->columns(['Column']);

$query->hasColumns(); // result: true

getColumns

Get insert into columns.

public function getColumns(): array

Example:

$query->columns(['Column1', 'Column2']);

$columns = $query->getColumns(); // result: ['`Column1`', '`Column2`']

clearColumns

Clear insert into columns.

public function clearColumns(): $this

Example:

$query->columns(['Column']);

$query->hasColumns(); // result: true

$query->clearColumns();

$query->hasColumns(); // result: false

values

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

hasValues

Determine if has insert values.

public function hasValues(): bool

Example:

$query->hasValues(); // result: false

$query->values(['value']);

$query->hasValues(); // result: true

getValues

Get insert values.

public function getValues(): array

Example:

$query->values(['value1', 'value2']);

$values = $query->getValues(); // result: ['value1', 'value2']

clearValues

Clear insert values.

public function clearValues(): $this

Example:

$query->values(['value']);

$query->hasValues(); // result: true

$query->clearValues();

$query->hasValues(); // result: false

data

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

clearData

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

select

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`

selectRaw

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`

hasSelect

Determine if has insert select.

public function hasSelect(): bool

Example:

$query->hasSelect(); // result: false

$query->selectRaw('Select `Column` from `Table2`');

$query->hasSelect(); // result: true

getSelect

Get insert select.

public function getSelect(): array

Example:

$query->selectRaw('Select `Column` from `Table2`');

$sql = $query->getSelect(); // result: Select `Column` from `Table2`

clearSelect

Clear insert select.

public function clearSelect(): $this

Example:

$query->selectRaw('Select `Column` from `Table2`');

$query->hasSelect(); // result: true

$query->clearSelect();

$query->hasSelect(); // result: false

toSql INSERT statement

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

toString INSERT statement

Get SQL statement.

public function toString(): string

Example:

$query->into('Table')->data(['Column' => 'value']);

echo $query->toString();
// INSERT INTO `Table` (`Column`) VALUES (?)

From Clause

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.

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`

fromRaw

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`

fromLogic

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` 

hasFrom

Determine if has from tables.

public function hasFrom(): bool

Example:

$query->hasFrom(); // result: false

$query->from('Table');

$query->hasFrom(); // result: true

getFrom

Get from tables.

public function getFrom(): array

Example:

$query->from('Table');

$sql = $query->getFrom();
//Array
//(
//    [Table] => Array
//        (
//            [tableKey] => Table
//            [table] => `Table`
//            [alias] => 
//            [params] => Array
//                (
//                )
//        )
//)

clearFrom

Clear from tables.

public function clearFrom(): $this

Example:

$query->from('Table');

$query->hasFrom(); // result: true

$query->clearFrom();

$query->hasFrom(); // result: false

fromToSql

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`', []]

fromToString

Get FROM SQL clause.

public function fromToString(?JoinClauseStrategy $join = null, bool $useClause = true): string

Example:

$query->from('Table');

echo $query->toString();
// FROM `Table`

toSql FROM clause

Get SQL clause with parameters.

public function toSql(?JoinClauseStrategy $join = null, bool $useClause = true): array

Example:

$query->from('Table');

$sql = $query->toSql();
// ['FROM `Table`', []]

toString FROM clause

Get SQL clause.

public function toString(?JoinClauseStrategy $join = null, bool $useClause = true): string

Example:

$query->from('Table');

echo $query->toString();
// FROM `Table`

Join Clause

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

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

leftOn

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

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

rightOn

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

Inner join.

Returns records that have matching values in both tables.

public function inner($table, string $on = null, string ...$params): $this

innerOn

Inner join with conditions.

Returns records that have matching values in both tables.

public function innerOn($table, $on): $this

cross

Cross join.

Return all records when there is a match in either left or right table.

public function cross($table): $this

leftTo

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

leftToOn

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

rightTo

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

rightToOn

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

innerTo

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

innerToOn

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

crossTo

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

joinLogic

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

hasJoin

Determine if has joins.

public function hasJoin(): bool

Example:

$query->hasJoin(); // result: false

$query->inner('Table');

$query->hasJoin(); // result: true

getJoin

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

clearJoin

Clear joins.

public function clearJoin(): $this

Example:

$query->inner('Table');

$query->hasJoin(); // result: true

$query->clearJoin();

$query->hasJoin(); // result: false

joinToSql

Get JOIN SQL clause with parameters.

public function joinToSql(string $source = null): array

Example:

$query->inner('Table');

$sql = $query->toSql();
// ['INNER JOIN `Table`', []]

joinToString

Get JOIN SQL clause.

public function joinToString(string $source = null): string

Example:

$query->inner('Table');

echo $query->toString();
// INNER JOIN `Table`

toSql JOIN clause

Get SQL clause with parameters.

public function toSql(string $source = null): array

Example:

$query->inner('Table');

$sql = $query->toSql();
// ['INNER JOIN `Table`', []]

toString JOIN clause

Get SQL clause.

public function toString(string $source = null): string

Example:

$query->inner('Table');

echo $query->toString();
// INNER JOIN `Table`

Where Clause

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;

where

Filter records with AND condition.

public function where(string|array $column, string $operator, string|array $value = null): $this

orWhere

Filter records with OR condition.

public function orWhere(string|array $column, string $operator, string|array $value = null): $this

whereMultiple

Filter records by column-value with AND condition.

public function whereMultiple(array $columns): $this

orWhereMultiple

Filter records by column-value with OR condition.

public function orWhereMultiple(array $columns): $this

whereDate

Filter records by date with AND condition.

public function whereDate(string|array $column, string $operator, string|array $value = null): $this

orWhereDate

Filter records by date with OR condition;

public function orWhereDate(string|array $column, string $operator, string|array $value = null): $this

whereTime

Filter records by time with AND condition.

public function whereTime(string|array $column, string $operator, string|array $value = null): $this

orWhereTime

Filter records by time with OR condition;

public function orWhereTime(string|array $column, string $operator, string|array $value = null): $this

whereYear

Filter records by year with AND condition.

public function whereYear(string|array $column, string $operator, string|array $value = null): $this

orWhereYear

Filter records by year with OR condition;

public function orWhereYear(string|array $column, string $operator, string|array $value = null): $this

whereMonth

Filter records by month with AND condition.

public function whereMonth(string|array $column, string $operator, string|array $value = null): $this

orWhereMonth

Filter records by month with OR condition;

public function orWhereMonth(string|array $column, string $operator, string|array $value = null): $this

whereDay

Filter records by day with AND condition.

public function whereDay(string|array $column, string $operator, string|array $value = null): $this

orWhereDay

Filter records by day with OR condition;

public function orWhereDay(string|array $column, string $operator, string|array $value = null): $this

whereRelation

Filter records by column relation with AND condition.

public function whereRelation(string|array $column1, string $operator, string|array $column2 = null): $this

orWhereRelation

Filter records by column relation with OR condition.

public function orWhereRelation(string|array $column1, string $operator, string|array $column2 = null): $this

whereRelations

Filter records by column-column relations with AND condition.

public function whereRelations(array $relations): $this

orWhereRelations

Filter records by column-column relations with OR condition.

public function orWhereRelations(array $relations): $this

whereIs

Filter records by TRUE column with AND condition.

public function whereIs(string $column): $this

orWhereIs

Filter records by TRUE column with OR condition.

public function orWhereIs(string $column): $this

whereIsNot

Filter records by FALSE column with AND condition.

public function whereIsNotNull(string $column): $this

orWhereIsNot

Filter records by FALSE column with OR condition.

public function orWhereIsNotNull(string $column): $this

whereIsNull

Filter records by NULL column with AND condition.

public function whereIsNull(string $column): $this

orWhereIsNull

Filter records by NULL column with OR condition.

public function orWhereIsNull(string $column): $this

whereIsNotNull

Filter records by NOT NULL column with AND condition.

public function whereIsNotNull(string $column): $this

orWhereIsNotNull

Filter records by NOT NULL column with OR condition.

public function orWhereIsNotNull(string $column): $this

whereBetween

Filter records by column between values with AND condition.

public function whereBetween(string $column, int $min, int $max): $this

orWhereBetween

Filter records by column between values with OR condition.

public function orWhereBetween(string $column, int $min, int $max): $this

whereNotBetween

Filter records by column not between values with AND condition.

public function whereNotBetween(string $column, int $min, int $max): $this

orWhereNotBetween

Filter records by column not between values with OR condition.

public function orWhereNotBetween(string $column, int $min, int $max): $this

whereConditions

Filter records by conditions with AND condition.

public function whereConditions(callable|Conditions|WhereClauseStrategy|HavingClauseStrategy $conditions): $this

orWhereConditions

Filter records by conditions with OR condition.

public function orWhereConditions(callable|Conditions|WhereClauseStrategy|HavingClauseStrategy $conditions): $this

whereRaw

Filter records by raw SQL with AND condition.

public function whereRaw(string $sql, string ...$params): $this

orWhereRaw

Filter records by raw SQL with OR condition.

public function orWhereRaw(string $sql, string ...$params): $this

whereLogic

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

hasWhere

Determine if has where conditions.

public function hasWhere(): bool

Example:

$query->hasWhere(); // result: false

$query->where('Column', 'value');

$query->hasWhere(); // result: true

getWhere

Get where conditions.

public function getWhere(): array

clearWhere

Clear where conditions.

public function clearWhere(): $this

Example:

$query->where('Column', 'value');

$query->hasWhere(); // result: true

$query->clearWhere();

$query->hasWhere(); // result: false

whereExists

Filter records by SELECT if exists.

public function whereExists(SelectQuery $sql): $this

whereNotExists

Filter records by SELECT statement if not exists.

public function whereNotExists(SelectQuery $sql): $this

whereExistsRaw

Filter records by raw SELECT statement if exists.

public function whereExistsRaw(string $sql, string ...$params): $this

whereNotExistsRaw

Filter records by raw SELECT statement if not exists.

public function whereNotExistsRaw(string $sql, string ...$params): $this

hasExists

Determine if has exists SELECT statement.

public function hasExists(): bool

getExists

Get exists SELECT statement.

public function getExists(): array

clearExists

Clear exists SELECT statement.

public function clearExists(): $this

whereToSql

Get WHERE SQL clause with parameters.

public function whereToSql(bool $useClause = true): array

joinToString

Get WHERE SQL clause.

public function whereToString(bool $useClause = true): string

toSql WHERE clause

Get SQL clause with parameters.

public function toSql(bool $useClause = true): array

toString WHERE clause

Get SQL clause.

public function toString(bool $useClause = true): string

Group By Clause

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.

public function groupBy(string $column): $this

groupByRaw

Group by raw columns.

public function groupByRaw(string $sql, string ...$params): $this

groupByLogic

Define custom group by logic.

public function groupByLogic(string $sql, array $params = []): $this

hasGroupBy

Determine if has group by columns.

public function hasGroupBy(): bool

getGroupBy

Get group by columns.

public function getGroupBy(): array

clearGroupBy

Clear group by columns.

public function clearGroupBy(): $this

groupByToSql

Get GROUP BY SQL clause with parameters.

public function groupByToSql(bool $useClause = true): array

groupByToString

Get GROUP BY SQL clause.

public function groupByToString(bool $useClause = true): string

toSql WHERE clause

Get SQL clause with parameters.

public function toSql(bool $useClause = true): array

toString WHERE clause

Get SQL clause.

public function toString(bool $useClause = true): string

Having Clause

HAVING clause.

List of magic methods:

List of supported methods:

Order By Clause

ORDER BY clause.

List of magic methods:

List of supported methods:

Limit Clause

LIMIT clause.

List of supported methods:

Offset Clause

OFFSET clause.

List of supported methods:

Conditions

Conditions.

List of magic methods:

List of supported methods: