Query Builder
Building on top of the foundations laid by DAO is Yii's Query Builder. Yii's Query Builder allows us to write database-agnostic queries in a programmatic way. Consequently, queries written through the Query Builder are significantly more readable than their DAO counterparts.
The basics of Query Builder involve the creation an instance of yii\db\Query
, the construction of a statement, and then the execution of that query statement. For example, we could simply query for all the users in our database in Query Builder using the following code:
$users = (new \yii\db\Query()) ->select(['id', 'email']) ->from('user') ->all();
Tip
When working with Query Builder, we're actually using the yii\db\Query
class rather than yii\db\QueryBuilder
. While yii\db\QueryBuilder
can generate SQL statements similar to those generated by yii\db\Query
, yii\db\Query
enables these statements to be database-agnostic. In general, you'll...