yii2 gridview 过滤第二个表列上的计数/总和

lei*_*ila 2 php gridview filter yii2

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

lei*_*ila 5

我找到了答案。

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)