你可以做到这一点,那么你的访客数可以成为你的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,
));
}
...
}
在你的模型,你就需要声明一个变量来保存计数的搜索,然后添加到这个搜索()方法,像这样;
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',
),
),
));
我没有测试过,但我从我自己的项目的一个更复杂的模型剥离它,所以它可能需要一些编辑和变量名,将最有可能需要改变你的应用程序,但基本的流程就在那里。
嗨Stu, 首先非常感谢你。我的问题是解决我在谷歌上搜索了4天,但仍然没有找到任何解决方案。如果可以的话,谢谢 我只想使用自定义排序,我的意思是哪个主机名为我们提供了足够的访问者,这个主机在CGridview中向上移动。可能需要一个自定义功能,但怎么能,我无法解决这个问题。 '主机名游客计数详细 facbook.com 40点击这里 google.com 150点击这里 yahoo.com 90点击这里' – 2013-03-20 10:43:15
我想谷歌移动顶行,我怎么能解决这个问题,我在很多请麻烦。 – 2013-03-20 10:50:34
与上面它应该自动按'visit_count DESC'命令?您还应该能够点击访问计数列标题以按该列进行排序? – Stu 2013-03-20 11:13:43