yii2 gridview过滤第二个表列

时间:2016-09-28 09:18:57

标签: php gridview filter yii2

我有这些相关的表:orderorder_product (order_id, product_id, quantity, product_price)product。 我正在使用yii2网格视图来显示订单模型,其中可以在sql中计算的总金额 select SUM(p.quantity*p.product_price)total from order_product p GROUP by order_id 或者使用php getter和订购的产品数量,我可以通过hasmany轻松获得。 我的问题是gridview过滤器。 如何在gridview中设置这些列的搜索和排序?

1 个答案:

答案 0 :(得分:4)

我找到了答案。

<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Order;
use common\models\OrderProduct;
class OrderSearch extends Order
{
    public $total;
    public $nbProd;
    public $client;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['total', 'nbProd', 'client'], 'safe'],
            [['nbProd'], 'number'],
            [['client'], 'string'],
        ];
    }
    public function search($params)
    {
        $query = Order::find();
        $query->joinWith(['customer']);
        $subQuery = OrderProduct::find()
        ->select('order_id, SUM(quantity*product_price) as total,               count(product_id) as nbProd')
        ->groupBy('order_id');
        $query->leftJoin(['orderSum' => $subQuery], 'orderSum.order_id = order.id');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
        ]);
        $dataProvider->sort->attributes['client'] = [
            'asc' => ['customer.company' => SORT_ASC],
            'desc' => ['customer.company' => SORT_DESC],
        ];
        $dataProvider->sort->attributes['nbProd'] = [
            'asc' => ['orderSum.nbProd' => SORT_ASC],
            'desc' => ['orderSum.nbProd' => SORT_DESC],
        ];
        $dataProvider->sort->attributes['total'] = [
            'asc' => ['orderSum.total' => SORT_ASC],
            'desc' => ['orderSum.total' => SORT_DESC],
        ];

        $this->load($params);

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

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'orderSum.total' => $this->total,
            'orderSum.nbProd' => $this->nbProd,
        ]);

        $query->andFilterWhere(['like', 'customer.name', $this->client]);

        return $dataProvider;
    }
}