假如有一個User表,一個Post表,User表中關係如下
public function relations()
{
return array(
'posts' => array(self::HAS_MANY, 'Post', 'author_id');
);
}
當我們用直接用CGridView進行分頁展示的時候發現當前頁的條數竟然是以post的數目爲標準而不是user的 ,假定每頁5條可能展示的不足5條,Post的數量總和爲5條。同樣的情況也會出現在CActiveRecord::findAll 中。這個時候CDbCriteria中該如下定義
// query criteria
$criteria = new CDbCriteria();
// force to join Post (without selecting)
$criteria->with = array(
'posts' => array(
'together' => true,
'select' => false,
),
);
// compare title
$criteria->compare('posts.title', $searchWord, true);
// group by Author's id
$criteria->group = 't.id';
// order by author name
$criteria->order = 't.name ASC';
// limit to 5 authors
$criteria->limit = 5;
// find all authors
$authors = User::model()->findAll($criteria);