20.11.2014 Views

O Guia Definitivo do Yii 1.1

O Guia Definitivo do Yii 1.1

O Guia Definitivo do Yii 1.1

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

$sql = <strong>Yii</strong>::app()->db->createCommand()<br />

->select('*')<br />

->from('tbl_user')<br />

->text;<br />

If there are any parameters to be bound to the query, they can be retrieved via the<br />

CDbCommand::params property.<br />

Alternative Syntax for Building Queries<br />

Sometimes, using method chaining to build a query may not be the optimal choice. The <strong>Yii</strong><br />

Query Builder allows a query to be built using simple object property assignments. In<br />

particular, for each query builder method, there is a corresponding property that has the<br />

same name. Assigning a value to the property is equivalent to calling the corresponding<br />

method. For example, the following two statements are equivalent, assuming $command<br />

represents a CDbCommand object:<br />

$command->select(array('id', 'username'));<br />

$command->select = array('id', 'username');<br />

Furthermore, the CDbConnection::createCommand() method can take an array as the<br />

parameter. The name-value pairs in the array will be used to initialize the properties of the<br />

created CDbCommand instance. This means, we can use the following code to build a<br />

query:<br />

$row = <strong>Yii</strong>::app()->db->createCommand(array(<br />

'select' => array('id', 'username'),<br />

'from' => 'tbl_user',<br />

'where' => 'id=:id',<br />

'params' => array(':id'=>1),<br />

))->queryRow();<br />

Building Multiple Queries<br />

A CDbCommand instance can be reused multiple times to build several queries. Before<br />

building a new query, however, the CDbCommand::reset() method must be invoked to<br />

clean up the previous query. For example:<br />

$command = <strong>Yii</strong>::app()->createCommand();<br />

$users = $command->select('*')->from('tbl_users')->queryAll();<br />

$command->reset(); // clean up the previous query<br />

$posts = $command->select('*')->from('tbl_posts')->queryAll();<br />

Building Data Manipulation Queries

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!