Yii2按计算的相关字段排序

时间:2017-12-22 08:02:25

标签: php gridview yii2

在过去的几个小时里,我试图创建一个gridview可排序的计算列而没有成功,我尝试了每个指南,按照完全相同的步骤进行操作。

计算出的关系:

public function getOrderAmount() {
    return $this->hasMany(Transaction::className(), ['user_id' => 'id'])->sum('sum');
}

UserSearch模型:

class UserSearch extends User
{
    public $orderAmount;

    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['orderAmount'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = User::find();

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


        $dataProvider->setSort([
            'attributes'=>[
                'id',
                'name',
                'orderAmount'=>[
                    'asc'=>['orderSum.order_amount'=>SORT_ASC],
                    'desc'=>['orderSum.order_amount'=>SORT_DESC],
                    'label'=>'Order Name'
                ]
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere(['orderSum.order_amount'=>$this->orderAmount]);

        return $dataProvider;
    }
}

观点:

<?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'responsive' => true,
            'hover' => true,
            'perfectScrollbar' => true,
            'columns' => [
                        'orderAmount',
            ],
        ]); ?>

这是我在上面示例中所遵循的指南http://webtips.krajee.com/filter-sort-summary-data-gridview-yii-2-0/

我收到了错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orderSum.order_amount' in 'order clause'
The SQL being executed was: SELECT * FROM `tbl_users` WHERE `id` IN ('1', '56') ORDER BY `orderSum`.`order_amount` LIMIT 20

注意:我删除了其他代码块以便于调试。

1 个答案:

答案 0 :(得分:1)

 1054 Unknown column 'orderSum.order_amount' in 'order clause'

错误基本上说它找不到列,因为即使你在模型上声明了关系,你还没有使用它。

在您的UserSearch模型中,您应该在加载参数之前使用关系。

    $query->joinWith('orderAmount as oa');
    $this->load($params);

另外,请不要忘记在您的UserSearch模型上添加array_merge方法,因为您正在使用其他属性。

 public function attributes()
   {
     // add related fields to searchable attributes
     return array_merge(parent::attributes(), ['oa.order_amount ']);
   }

最后,由于我们将关系名称重写为“oa”,您应该将“orderAmount”更改为“oa”

         $dataProvider->setSort([
        'attributes'=>[
            'id',
            'name',
            'orderAmount'=>[
                'asc'=>['oa.order_amount'=>SORT_ASC],
                'desc'=>['oa.order_amount'=>SORT_DESC],
                'label'=>'Order Name'
            ]
        ]
    ]);