Yii provides a basic database access layer as described in the [Database basics](database-basics.md) section. The database access layer provides a low-level way to interact with the database. While useful in some situations, it can be tedious to rely too much upon direct SQL. An alternative approach that Yii provides is the Query Builder. The Query Builder provides an object-oriented vehicle for generating queries to be executed.
Yii provides a basic database access layer as described in the [Database basics](database-basics.md) section.
The database access layer provides a low-level way to interact with the database. While useful in some situations,
it can be tedious and error-prone to write raw SQLs. An alternative approach is to use the Query Builder.
The Query Builder provides an object-oriented vehicle for generating queries to be executed.
Here's a basic example:
A typical usage of the query builder looks like the following:
In the following, we will explain how to build various clauses in a SQL statement. For simplicity,
we use `$query` to represent a [[yii\db\Query]] object.
`SELECT`
--------
In order to form a basic `SELECT` query, you need to specify what columns to select and from what table:
...
...
@@ -31,39 +45,82 @@ $query->select('id, name')
->from('tbl_user');
```
Select options can be specified as a comma-separated string, as in the above, or as an array. The array syntax is especially useful when forming the selection dynamically:
Select options can be specified as a comma-separated string, as in the above, or as an array.
The array syntax is especially useful when forming the selection dynamically:
```php
$columns=[];
$columns[]='id';
$columns[]='name';
$query->select($columns)
$query->select(['id','name'])
->from('tbl_user');
```
> Info: If your `SELECT` contains SQL expressions which use commas (e.g. `CONCAT(first_name, last_name) AS full_name`),
> you should use an array instead of a string to represent the columns being selected. Your SQL expressions may be
> split by commas into several parts.
> Info: You should always use the array format if your `SELECT` clause contains SQL expressions.
> This is because a SQL expression like `CONCAT(first_name, last_name) AS full_name` may contain commas.
> If you list it together with other columns in a string, the expression may be split into several parts
> by commas, which is not what you want to see.
When specifying columns, you may include the table prefixes or column aliases, e.g., `tbl_user.id`, `tbl_user.id AS user_id`.
If you are using array to specify the columns, you may also use the array keys to specify the column aliases,
Usually data is selected based upon certain criteria. Query Builder has some useful methods to specify these, the most powerful of which being `where`. It can be used in multiple ways.
...
...
@@ -185,7 +250,7 @@ In case `$search` isn't empty the following SQL will be generated:
WHERE(`status`=10)AND(`title`LIKE'%yii%')
```
Order
`ORDER BY`
-----
For ordering results `orderBy` and `addOrderBy` could be used:
...
...
@@ -199,13 +264,6 @@ $query->orderBy([
Here we are ordering by `id` ascending and then by `name` descending.
Distinct
--------
If you want to get IDs of all users with posts you can use `DISTINCT`. With query builder it will look like the following:
- Enh #2156: `yii migrate` now automatically creates `migrations` directory if it does not exist (samdark)
- Enh:#2211: Added typecast database types into php types (dizews)
- Enh #2240: Improved `yii\web\AssetManager::publish()`, `yii\web\AssetManager::getPublishedPath()` and `yii\web\AssetManager::getPublishedUrl()` to support aliases (vova07)
- Enh #2325: Adding support for the `X-HTTP-Method-Override` header in `yii\web\Request::getMethod()` (pawzar)
- Enh #2364: Take into account current error reporting level in error handler (gureedo)
- Enh: Added support for using arrays as option values for console commands (qiangxue)
- Enh: Added `favicon.ico` and `robots.txt` to default application templates (samdark)
- Enh: Added `Widget::autoIdPrefix` to support prefixing automatically generated widget IDs (qiangxue)
- Enh: Improved `QueryBuilder::buildLimit()` to support big numbers (qiangxue)
- Enh:#2211: Added typecast database types into php types (dizews)
- Enh #2240: Improved `yii\web\AssetManager::publish()`, `yii\web\AssetManager::getPublishedPath()` and `yii\web\AssetManager::getPublishedUrl()` to support aliases (vova07)
- Enh #2325: Adding support for the `X-HTTP-Method-Override` header in `yii\web\Request::getMethod()` (pawzar)
- Enh #2364: Take into account current error reporting level in error handler (gureedo)
- Enh: Added support for building SQLs with sub-queries (qiangxue)
- Chg #1519: `yii\web\User::loginRequired()` now returns the `Response` object instead of exiting the application (qiangxue)
- Chg #1586: `QueryBuilder::buildLikeCondition()` will now escape special characters and use percentage characters by default (qiangxue)
- Chg #1610: `Html::activeCheckboxList()` and `Html::activeRadioList()` will submit an empty string if no checkbox/radio is selected (qiangxue)