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

ncgqoxb0  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(451)

我想将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'],
        ],
    ]); ?>

但是它没有给我想要的输出,我哪里出错了,我怎么能这样做呢?

fnvucqvd

fnvucqvd1#

我已经用yii2db查询解决了这个问题。

$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;
klr1opcd

klr1opcd2#

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

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

或者你可以在adanalytics类的开始添加

public $totalccost;
0x6upsns

0x6upsns3#

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

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

你可以给这个属性添加标签

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

在网格视图列中

...
'cpview',
'totalcost'

您可以在任何地方使用此函数作为$model->totalcost

相关问题