Yii2:按计算列排序

时间:2017-05-28 14:30:36

标签: yii2 yii2-advanced-app yii2-model

我有一张表:

name
startDate
endDate
units
price

我在给定年份的gridview中显示它们如下(视图中的index.php):

$gridColumns = [
    'name',
    [
        'attribute' => 'january',
        'format' => 'currency',
        'value' => function ($data) {
            if(date("m", strtotime($data["startDate"])) == 1) {
                return ($data["price"]*$data["units"]);
            }
            else {
                return "";
            }
        },
        'options' => ['style' => 'max-width:20px;'],
        'pageSummary' => true,
    ],
    [
        'attribute' => 'february',
        'format' => 'currency',
        'value' => function ($data) {
            if(date("m", strtotime($data["startDate"])) == 2) {
                return ($data["price"]*$data["units"]);
            }
            else {
                return "";
            }
        },
        'pageSummary' => true,
    ],
    ... until month 12
];

在我的搜索模型中,我定义了:

public $january, $february, $march, $april, $may, $june, $july, $august, $september, $october, $november, $december;

将它们放在规则和定义属性中是安全的,以便获得带有可排序项目的网格标题

$dataProvider = new ActiveDataProvider([
    'query' => $query,
        'pagination' => [
            'pageSize' => 0,
        ],
    'sort' => [
        'defaultOrder' => [
            'name' => SORT_ASC,
        ],
        'attributes' => [
            'name',
            'units',
            'price',
            'january',
            'february',
            'march',
            'april',
            'may',
            'june',
            'july',
            'august',
            'september',
            'october',
            'november',
            'december',
        ],
    ],
]);

但是当我尝试按照其中一个月进行排序时,会出现如下错误:

  

例外' PDOException'消息' SQLSTATE [42S22]:列不   发现:1054未知专栏&1; '在'订单条款''

如何根据数据库中不存在的这些计算列进行排序?

由于

0 个答案:

没有答案