您可以通过将访问者计数添加到初始查询来做到这一点,然后您的访问者计数可以成为 CGridView 中的可排序列。
所以你的控制器可以看起来很正常;
class VisitsController extends Controller
{
...
public function actionIndex()
{
$model=new Visits('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Visits']))
$model->attributes=$_GET['Visits'];
$this->render('index',array(
'model'=>$model,
));
}
...
}
在您的模型中,您需要声明一个变量来保存计数搜索,然后将其添加到您的 search() 方法中,如下所示;
class Visits extends CActiveRecord
{
/**
* @var array Allows model filtering by visit count
*/
public $visit_count;
...
// Remember to declare it as safe
public function rules()
{
return array(
...
array(... ,'visit_count', ..., 'safe', 'on'=>'search'),
...
);
}
...
// Give it a label if you wish
public function attributeLabels()
{
return array(
...
'visit_count' => 'Visitors Counts',
...
);
}
...
// Now add to your search method
public function search()
{
$criteria=new CDbCriteria;
$visit_table = Visits::model()->tableName();
$visit_count_sql = "(select count(*) from `$visit_table` where `$visit_table`.`hostname` = `t`.`hostname`)";
$criteria->select = array(
'*',
$visit_count_sql . " as `visit_count`",
);
$criteria->compare($visit_count_sql, $this->visit_count);
// Set the CActiveDataProvider to order by the visitor count
$criteria->order = 'visit_count DESC';
...
// All your other criteria code
...
// And add to the CActiveDataProvider
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'visit_count'=>array(
'asc'=>'visit_count',
'desc'=>'visit_count DESC',
),
'*',
),
),
'pagination'=>array(
'pageSize'=>100,
),
));
}
...
}
然后,您可以将其添加到您的视图中的 CGridView;
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'visit-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'hostname',
'visit_count',
array(
// Whatever your detail column looks like!
),
array(
'class'=>'CButtonColumn',
),
),
));
我没有测试过,但是我已经从我自己的一个项目中的一个更复杂的模型中剥离了它,所以它很可能需要一些编辑,并且很可能需要为你的应用程序更改变量名,但基本流程是那里。