YII2 gridview排序两列值的总和

时间:2018-03-20 11:17:58

标签: php gridview yii2 yii2-model

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

这是gridview。

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

如何为此列添加排序?

1 个答案:

答案 0 :(得分:2)

好的,我没有完整的源代码,但可以帮助我找到一个基本的例子。 理想情况下,您应该首先使用Gii创建模型和CRUD文件,就像我在下面的示例中所做的那样。

这是我的基本数据库表record

enter image description here

我添加了一些测试数据:

enter image description here

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

  

@应用/模型/ 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());
    }
}
  

@应用/模型/ 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;
    }
}
  

@应用/视图/记录/ 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'],
        ],
    ]); ?>

我希望这有帮助!

enter image description here