Using CDbCriteria in the Yii Framework

July 24, 2013

The Yii Book If you like my writing on the Yii framework, you'll love "The Yii Book"!

The CDbCriteria class let’s you customize queries through an object. The first thing you should do to become more comfortable with Active Record when using the Yii framework is master usage of CDbCriteria.

This is an excerpt from Chapter 8, “Working with Databases,” of “The Yii Book“.

To start, create a CDbCriteria instance:

$criteria = new CDbCriteria();

Then you can customize it by assigning values to various properties, the most important of which are listed in the following table.

Property

Sets

condition

The WHERE clause

limit

The LIMIT value

offset

The offset value in a LIMIT clause

order

The ORDER BY clause

params

The variables to be bound to the parameters

select

The columns to be selected

There are also properties for grouping and aggregating results, discussed elsewhere in the book.

As an easy example to begin, the same findByPk() query can be accomplished in this manner:

Retrieving Multiple Records

The find() method only ever returns a single row (at most). If multiple rows should be returned by a query, use findAll() instead. Its signature is the same:

The class specification for the findAll() method.

The findAll() method will return an array of objects, if one or more records match. If no records match, findAll() returns an empty array. This differs from find(), which returns NULL if no match was found.

Counting Records

Sometimes, you don’t actually need to return rows of data, but just determine how many rows apply to the given criteria. If you just want to see how many rows would be found by a query, use Active Record’s count() method. It takes the criteria as the first argument and parameters as the second, just like find():