Yii2 Querybuilder与searchmodel

时间:2017-12-19 01:12:52

标签: php yii2 yii2-basic-app

我的搜索模型

$query = (new \yii\db\Query())
    ->select(['monthsubmit',"DATE_FORMAT(monthsubmit, '%m-%Y') as c_date", 'modeler', 'count(sku) as count'])
    ->from('sku3d')
    ->groupBy(['monthsubmit', 'modeler'])
    ->orderBy(['monthsubmit'=>SORT_DESC, 'modeler'=>SORT_DESC]);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

我的控制器

    $searchModel = new Sku3dSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

我的gridview

<?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'=>$searchModel,
    'pjax'=>true,
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,
        'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-user"></i>Submitted SKU by Month</h3>',
    ],
    'columns' => [
        [
        'attribute'=>'monthsubmit', 
        'width'=>'310px',
        'filter'=>ArrayHelper::map(Sku3d::find()->orderBy('monthsubmit')->asArray()->all(), 'monthsubmit', 'monthsubmit'), 
        'group'=>true,
    ],
        [
        'attribute'=>'modeler', 
        'width'=>'180px',
        'group'=>true,
        ],

        'count:text:Total Sku',
    ]
]); 
?> 

起初我没有在searchmodel中使用querybuilder,而是在控制器中,一切正常。但我需要过滤它,所以我将我的querybuilder移动到searchmodel。

当我这样做时,它出现错误“获取未知属性:app \ models \ Sku3d :: count”。

如何将'count(sku) as count'调用到我的gridview。而且看起来我的groupBy(['monthsubmit', 'modeler'])也不起作用。

请告诉我我哪里错了。

谢谢。

1 个答案:

答案 0 :(得分:2)

在您的searchmodel中添加一个publica var

class Sku3dSearch extends Sku3d
{

    public $count;

    /**
     * @inheritdoc
     */
    public function rules()

    ......





    $query = (new \yii\db\Query())
        ->select(['monthsubmit',"DATE_FORMAT(monthsubmit, '%m-%Y') as c_date", 'modeler', 'count(sku) as count'])
        ->from('sku3d')
        ->groupBy(['monthsubmit', 'modeler'])
        ->orderBy(['monthsubmit'=>SORT_DESC, 'modeler'=>SORT_DESC]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);


}