O Guia Definitivo do Yii 1.1
O Guia Definitivo do Yii 1.1
O Guia Definitivo do Yii 1.1
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
$user = <strong>Yii</strong>::app()->db->createCommand()<br />
->select('id, username, profile')<br />
->from('tbl_user u')<br />
->join('tbl_profile p', 'u.id=p.user_id')<br />
->where('id=:id', array(':id'=>$id))<br />
->queryRow();<br />
The Query Builder is best used when you need to assemble a SQL statement procedurally,<br />
or based on some conditional logic in your application. The main benefits of using the<br />
Query Builder include:<br />
• It allows building complex SQL statements programmatically.<br />
• It automatically quotes table names and column names to prevent conflict with SQL<br />
reserved words and special characters.<br />
• It also quotes parameter values and uses parameter binding when possible, which<br />
helps reduce risk of SQL injection attacks.<br />
• It offers certain degree of DB abstraction, which simplifies migration to different DB<br />
platforms.<br />
• It is not mandatory to use the Query Builder. In fact, if your queries are simple, it is<br />
easier and faster to directly write SQL statements.<br />
Preparing Query Builder<br />
The <strong>Yii</strong> Query Builder is provided in terms of CDbCommand, the main DB query class<br />
described in Data Access Objects.<br />
To start using the Query Builder, we create a new instance of CDbCommand as follows,<br />
$command = <strong>Yii</strong>::app()->db->createCommand();<br />
That is, we use <strong>Yii</strong>::app()->db to get the DB connection, and then call<br />
CDbConnection::createCommand() to create the needed command instance.<br />
Note that instead of passing a whole SQL statement to the createCommand() call as we<br />
<strong>do</strong> in Data Access Objects, we leave it empty. This is because we will build individual parts<br />
of the SQL statement using the Query Builder methods explained in the following.<br />
Building Data Retrieval Queries<br />
Data retrieval queries refer to SELECT SQL statements. The query builder provides a set<br />
of methods to build individual parts of a SELECT statement. Because all these methods<br />
return the CDbCommand instance, we can call them using method chaining, as shown in<br />
the example at the beginning of this section.<br />
• select: specifies the SELECT part of the query<br />
• selectDistinct: specifies the SELECT part of the query and turns on the DISTINCT<br />
flag<br />
• from: specifies the FROM part of the query