如何在yii2网格视图中乘以两列

时间:2018-04-26 10:43:35

标签: php mysql gridview yii2

我想在yii2网格中乘以两列,网格视图如下

<?= GridView::widget([
        //'dataProvider' => $dataProvider,
        'dataProvider'=>new ActiveDataProvider([
          'query' => Adanalytics::find()->
                where(['publisher_id' =>  Yii::$app->user->identity->id ])->
                select('id,ad_id,MAX(impression) AS impression, MAX(view) AS view, MAX(clicks) AS clicks,MAX(cpc) AS cpclick,MAX(cpv) AS cpview, (MAX(clicks)*MAX(cpc)) AS totalccost')->
                groupBy('ad_id, visitor_ip'),
        ]),
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'id',
            'ad_id',
            //'advertiser_id',
            //'publisher_id',
            //'visitor_ip',
            //'type_ad',
            'impression',
            'view',
            'clicks',
            //'placed_date',
            //'cpc',
            //'cpv',
            'cpclick',
            'cpview',
            'totalccost',
            //'cpi',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

但它没有给我想要的输出我错了怎么办呢?

3 个答案:

答案 0 :(得分:0)

如果您只需要将列作为gridview中的显示值,则可以创建计算列。

'cpview',
[
    'label' => 'Totalcost',
    'value' => function($model){
        return $model->cpclick * $model->clicks;
    }
],

否则您可以在Adanalytics课程的开头添加

public $totalccost;

答案 1 :(得分:0)

如果您想在任何地方使用计算,可以执行以下操作。 在你的模型中

yourTableBodyJqueryRefference.append(readXML(yourXmlString));

您可以为此属性添加标签

public function getTotalcost() 
{
   return $this->clicks * $this->cpclick; 
}

在网格视图列

public function attributeLabels()
{
    return [
        ...
        'totalcost' => Yii::t('app', 'Total cost'),
    ];
}

您可以在$ model-&gt; totalcost

的任何位置使用此功能

答案 2 :(得分:0)

我已经通过使用yii2 db query解决了这个问题,就像这样。

$subquery = Adanalytics::find()->
            select('id,ad_id,date_event,max(cpc) cpclick,max(cpv) cpview,max(impression) impression,max(view) view,max(clicks) clicks,visitor_ip,publisher_id')->
            from('ad_analytics')->
            where(['publisher_id' =>  Yii::$app->user->identity->id ])->
            groupBy('ad_id,date_event,visitor_ip');
  $query=Adanalytics::find()->
        select('ad_id,date_event,sum(cpclick) total_click_cost,sum(cpview) total_view_cost,sum(impression) total_impression,sum(view) total_views,sum(clicks) total_clicks,publisher_id')->
        from(['t'=>$subquery])->
        groupBy('t.ad_id,t.date_event');

并在网格视图中调用该列。

'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'ad_id',
        'total_impression',
        'total_views',
        'total_clicks',
        'total_click_cost',
        'total_view_cost',
        'date_event',


        ['class' => 'yii\grid\ActionColumn'],
    ],

在调用之前在模型中定义它们。

  public $total_click_cost;
   public $total_view_cost;
   public $total_impression;
   public $total_views;
   public $total_clicks;