Sort data

Hi all,

In my database have 2 table: book and chapter. Each book has many chapter. How can I sort the book by number of chapter? I can do this by SQL, but using ActiveRecord is different.

Thank you.

Look at the AR section of the guide - relations() under relational AR. You could define a STAT relation to get that info.

  1. You can use beforeFind event and get its criteria to apply the sort by chapter

// example

public function beforeFind()


 $this->getCDbCriteria()->order='chapter DESC';

 return parent::beforeFind();


  1. Use defaultScope

  2. Use a custom criteria with your find, findAll, findByPk, etc… methods. They all accept a criteria.

But, be very careful using that with a CGridView or CViewList, once you click on order, the order sql statement will be included twice:

dniznick: I already defined a STAT relation to get chapter count, but when applied to a CActiveDataProvider it get an error.

This is my code

$criteria = new CDbCriteria();


// I already a STAT relation named chapterNum in Book model

// $_GET['sort'] equal 'chapterNum'

$sort=new CSort('Book');

if (isset($_GET['sort'])) {







$books = new CActiveDataProvider('Book', array(

                    'criteria' => $criteria,

                    'pagination' => array(

                        'pageSize' => 20,




@Antonio Ramirez

I sort the book by quantity of book’s chapters. But I can’t do this in order statement. Can you explain it more clearly?

Finally, I got the solution though it looks like a trick, I hope Qiang Xue will fix this problem soon.