The previous article describes the way PHP uses DAO (Database Access object interface) to access a database, using DAO requires programmers to write SQL statements, and for some complex SQL statements, Yii provides query Builder to help programmers generate SQL statements, query Builder provides an object-oriented method for dynamically creating SQL statements, making a less-than-appropriate comparison, the PHP DAO and. Net DAO interfaces are very type, and Query Builder is a bit like LINQ, although it's much less functional than LINQ. For some simple SQL queries, there is usually no need to use query Builder, such as the lookup employee table in the previous article.
Using Query Builder has the following benefits compared to using SQL statements directly:
Enables the creation of more complex SQL queries dynamically through programs.
Automatically adds quotation marks to the table name and list in the SQL statement that is created to avoid conflicts with SQL-reserved identifiers.
Specify quotation marks for parameters and use parameter binding as much as possible to reduce the risk of SQL injection ...
Using Query Builder does not directly write SQL statements, but provides some degree of database abstraction, which facilitates switching database types.
This example queries Chinook's two table customer and employee to inquire about all customer contact information for employeeid=4 management.
If you are using SQL queries, you can write:
SELECT C.firstname, C.lastname, c.address,c.email from
customer C
INNER JOIN
employee E on
c. Supportrepid=e.employeeid
WHERE e.employeeid=4
This example uses Query Builder to create an SQL query that modifies the Sitecontroller Indexaction method:
Public Function Actionindex () {$model = array ();
$connection =yii::app ()->db;
$command = $connection->createcommand ()->select (' C.firstname, C.lastname, C.address,c.email ') ->from (' Customer C ')->join (' Employee e ', ' C.supportrepid=e.employeeid ')->where (' E.E
Mployeeid=4 ');
$dataReader = $command->query (); Each $row was an array representing a row of data foreach ($dataReader as $row) {$custome
R= new Datamodel ();
$customer->firstname= $row [' FirstName '];
$customer->lastname= $row [' LastName '];
$customer->address= $row [' address '];
$customer->email= $row [' email '];
$model []= $customer;
$this->render (' index ', array (' model ' => $model,));}
You can see that Query Builder also uses Cdbcommand, Cdbcommand provides the following methods for querying data:
Select ()
SelectDistinct ()
From ()
Where ()
Join ()
Leftjoin ()
Rightjoin ()
CrossJoin ()
Naturaljoin ()
Group ()
Having ()
Order ()
Limit ()
Offset ()
Union ()