YII2 gridview对两列的值求和 [英] YII2 gridview sort sum of values of two columns

查看:380
本文介绍了YII2 gridview对两列的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地在gridview中显示了3列. attr1,attr2以及这两个属性的总和. attr1和attr2来自数据库,第三列是它们的总和.如何进行排序和过滤?

I successfully displayed the 3 columns in the gridview. the attr1, attr2, and the sum of the 2 attributes. attr1 and attr2 are from the database and the 3rd column is their sum. How do I make the sorting and filtering work?

这是gridview.

Here is the gridview.

        [
            'label' => 'Number of Enquiries',
            'value' => function ($model) {
                return $model->countEnquire + $model->countPhone + $model->countTrial;
            },
            'enableSorting' => true,
        ]

如何为此列添加排序?

推荐答案

好的,我没有您要使用的完整源代码,但是可以提供一个基本示例. 理想情况下,您应该使用 Gii 就像我在下面的示例中一样.

OK, I don't have your full source code to go by but can help with a basic example. Ideally you should start by creating your model and CRUD files using Gii like I have for in my example below.

这是我的基本数据库表,record:

Here is my basic database table, record:

我添加了一些测试数据:

I added some test data:

然后,我使用Gii创建了模型和CRUD文件,然后对其进行了修改,以向您展示您希望实现的自定义求和/排序的示例.见下文.

Then I created the model and CRUD files using Gii, which I then modified to show you an example of the custom summing/sorting you wish to achieve. See below.

@ app/models/Record.php

@app/models/Record.php

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "record".
 *
 * @property integer $record_id
 * @property integer $attr1
 * @property integer $attr2
 * @property integer $sum
 */
class Record extends \yii\db\ActiveRecord
{
    public $sum;

    public function getSum()
    {
        $this->sum = 0;

        if (is_numeric($this->attr1) && is_numeric($this->attr2)) {
            $this->sum = $this->attr1 + $this->attr2;
        }

        return $this->sum;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'record';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['record_id', 'attr1', 'attr2'], 'required'],
            [['record_id', 'attr1', 'attr2', 'sum'], 'integer'],
            [['sum'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'record_id' => 'Record ID',
            'attr1' => 'Attr1',
            'attr2' => 'Attr2',
            'sum' => 'Sum',
        ];
    }

    /**
     * @inheritdoc
     * @return RecordQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new RecordQuery(get_called_class());
    }
}

@ app/models/RecordSearch.php

@app/models/RecordSearch.php

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Record;

/**
 * RecordSearch represents the model behind the search form about `app\models\Record`.
 */
class RecordSearch extends Record
{

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        // add related fields to searchable attributes
        return array_merge(parent::attributes(), ['sum']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['record_id', 'attr1', 'attr2', 'sum'], 'integer'],
            [['sum'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        // find records, additionally selecting the sum of the 2 fields as 'sum'
        $query = Record::find()->select('*, (`attr1` + `attr2`) AS `sum`');

        // add conditions that should always apply here

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

        // enable sorting for the related columns
        $dataProvider->sort->attributes['sum'] = [
            'asc' => ['sum' => SORT_ASC],
            'desc' => ['sum' => SORT_DESC],
        ];

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'record_id' => $this->record_id,
            'attr1' => $this->attr1,
            'attr2' => $this->attr2,
        ]);

        // if the sum has a numeric filter value set, apply the filter in the HAVING clause
        if (is_numeric($this->sum)) {
            $query->having([
                'sum' => $this->sum,
            ]);
        }

        return $dataProvider;
    }
}

@ app/views/record/index.php

@app/views/record/index.php

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel app\models\RecordSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Records';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="record-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Record', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
<?php Pjax::begin(); ?>    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'record_id',
            'attr1',
            'attr2',
            'sum',

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

我希望这会有所帮助!

I hope this helps!

这篇关于YII2 gridview对两列的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆