gridview对两列值的总和进行排序

gridview对两列值的总和进行排序

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

问题描述

我成功地在 gridview 中显示了 3 列.attr1、attr2 和 2 个属性的总和.attr1 和 attr2 来自数据库,第三列是它们的总和.如何使排序和过滤工作?

这是网格视图.

 ['标签' =>'查询次数','价值' =>功能($模型){返回 $model->countEnquire + $model->countPhone + $model->countTrial;},'启用排序' =>真的,]

如何为该列添加排序?

解决方案

好的,我没有你的完整源代码,但可以帮助提供一个基本示例.理想情况下,您应该首先使用

我添加了一些测试数据:

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

@app/models/Record.php

attr1) && is_numeric($this->attr2)) {$this->sum = $this->attr1 + $this->attr2;}返回 $this->sum;}/*** @inheritdoc*/公共静态函数表名(){返回记录";}/*** @inheritdoc*/公共函数规则(){返回 [[['record_id', 'attr1', 'attr2'], 'required'],[['record_id', 'attr1', 'attr2', 'sum'], 'integer'],[['总和'],'安全'],];}/*** @inheritdoc*/公共函数attributeLabels(){返回 ['record_id' =>'记录ID','属性1' =>'属性1','属性2' =>'属性2','总和' =>'和',];}/*** @inheritdoc* @return RecordQuery 这个 AR 类使用的活动查询.*/公共静态函数 find(){返回新的 RecordQuery(get_Called_class());}}

@app/models/RecordSearch.php

$查询,]);//启用对相关列的排序$dataProvider->sort->attributes['sum'] = ['asc' =>['总和' =>SORT_ASC],'desc' =>['总和' =>SORT_DESC],];$this->load($params);如果 (!$this->validate()) {//如果您不想在验证失败时返回任何记录,请取消注释以下行//$query->where('0=1');返回 $dataProvider;}//网格过滤条件$query->andFilterWhere(['record_id' =>$this->record_id,'属性1' =>$this->attr1,'属性2' =>$this->attr2,]);//如果总和设置了数字过滤器值,则在 HAVING 子句中应用过滤器如果 (is_numeric($this->sum)) {$query->have(['总和' =>$this->sum,]);}返回 $dataProvider;}}

@app/views/record/index.php

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(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yiigridSerialColumn'],'record_id','属性1','属性2','和',['类' =>'yiigridActionColumn'],],]);?>

我希望这会有所帮助!

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?

Here is the gridview.

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

How add sorting for this column?

解决方案

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.

Here is my basic database table, record:

I added some test data:

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.

<?php

namespace appmodels;

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 yiidbActiveRecord
{
    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());
    }
}
<?php

namespace appmodels;

use Yii;
use yiiaseModel;
use yiidataActiveDataProvider;
use appmodelsRecord;

/**
 * RecordSearch represents the model behind the search form about `appmodelsRecord`.
 */
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;
    }
}
<?php

use yiihelpersHtml;
use yiigridGridView;
use yiiwidgetsPjax;
/* @var $this yiiwebView */
/* @var $searchModel appmodelsRecordSearch */
/* @var $dataProvider yiidataActiveDataProvider */

$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' => 'yiigridSerialColumn'],

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

            ['class' => 'yiigridActionColumn'],
        ],
    ]); ?>

I hope this helps!

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

08-13 17:11