0

I have a calculated column I wanna have sortable. I have a get method for it...

public function getCur_margin() {
        return number_format(($this->store_cost / $this->store_price) / $this->store_cost * 100, 2) . '%';
    }

And I followed this thread...

CGridview custom field sortable

But now it's looking for an actual column in the database. How can I fetch a field using <calculations> AS cur_margin only temporarily for this CActiveDataProvider?

Here is the controller code for the provider:

$dataProvider = new CActiveDataProvider('Products', array(
    'criteria' => array(
        'condition' => 'store_id IN (SELECT `id` FROM `stores` WHERE `user_id` = ' . Yii::app()->user->id . ')',
    ),
    'pagination' => array(
        'pageSize' => 15,
    ),
    'sort'=>array(
        'attributes'=>array(
            'cur_margin' => array(
                'asc' => 'cur_margin ASC',
                'desc' => 'cur_margin DESC',
            ),
        ),
    ),
));
4

1 回答 1

3

您是否尝试在select的属性中指定您的自定义字段CDbCriteria

'select' => array(
    ...,   // fields to select
    '(<calculations>) AS cur_margin'
)

然后您不必声明 getCur_margin() 方法,而只需$cur_margin在模型中声明一个公共成员。所有需要的计算都将在 SQL 查询中完成。

您也可以参考此线程作为示例。

于 2013-06-20T09:12:22.017 回答