在GridView中过滤相关模型的设置

时间:2015-02-02 19:17:51

标签: php gridview yii yii2

我正在尝试在Yii2的GridView窗口小部件中为相关模型设置过滤器,但我不断得到错误,因为过滤器值必须是整数。

我已关注this question。现在,我有两个模型Services.phpServiceCharge.php

ServiceCharge.php中,关系设置如下:

public function getServiceName()
    {
        return $this->hasOne(Services::className(),['id'=>'service_name']);
    }

ServiceChargeSearch.php中,代码是这样的:

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ServiceCharges;

/**
 * ServiceChargesSearch represents the model behind the search form about `app\models\ServiceCharges`.
 */
class ServiceChargesSearch extends ServiceCharges
{
    /**
     * @inheritdoc
     */
    public function attributes()
    {
        // add related fields to searchable attributes
      return array_merge(parent::attributes(), ['serviceName.services']);

    }
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['charges_cash', 'charges_cashless'], 'number'],
            [['id', 'serviceName.services', 'room_category'], '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)
    {
        $query = ServiceCharges::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $dataProvider->sort->attributes['serviceName.services'] = [
        'asc' => ['serviceName.services' => SORT_ASC],
        'desc' => ['serviceName.services' => SORT_DESC],
        ];

$query->joinWith(['serviceName']); 

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
           // 'service_name' => $this->service_name,
            'room_category' => $this->room_category,
            'charges_cash' => $this->charges_cash,
            'charges_cashless' => $this->charges_cashless,
        ])
      ->andFilterWhere(['LIKE', 'serviceName.services', $this->getAttribute('serviceName.services')]);

        return $dataProvider;
    }
}

在我的Gridview中,它设置如下:

[
                'attribute'=>'service_name',
                'value'=>'serviceName.services',

            ],

正确显示相关模型的服务名称。

我无法看到我做错了什么,但服务属性的过滤字段根本没有显示。

2 个答案:

答案 0 :(得分:11)

实际上它比看起来简单得多。

  1. column_name添加到安全属性。 注意:这应该是名称

  2. 使用查询添加联接 - 例如 - $query->joinWith(['serviceName','roomCategory']);

  3. 添加过滤条件,如:

    ->andFilterWhere(['like', 'services.services', $this->service_name])
    ->andFilterWhere(['like', 'room_category.room_category', $this->room_category]);
    
  4. 如果要添加排序,请添加以下代码:

    $dataProvider->sort->attributes['service_name'] = [
        'asc'  => ['services.services' => SORT_ASC],
        'desc' => ['services.services' => SORT_DESC],
    ];
    $dataProvider->sort->attributes['room_category'] = [
        'asc'  => ['room_category.room_category' => SORT_ASC],
        'desc' => ['room_category.room_category' => SORT_DESC],
    ];
    
  5. 5您还应该设置关系名称public $roomCategory

    那就是它。相关表的排序和过滤都很完美。

    注意:删除gii生成的相关列和默认过滤的默认验证,如整数,否则会产生错误。

    最新版本更新:

    • 不需要添加Public $属性。
    • 也不需要为关系添加安全属性。
    • 但是您想要过滤的当前模型中的属性是 添加到必须的安全属性。
    • 最重要的是在你的gridview中,相关属性必须 处于封闭格式。

    即示例

    [
    'attribute=>'attribute_name',
    'value=function($data){
         return $data->relationname->related_table_attribute_name
    }
    ],
    

    请记住,您使用的relation_name.related_table_attribute_name过滤器对某些人来说并不起作用。

答案 1 :(得分:0)

有一套相当全面的说明on the Yii Framework website。唯一需要注意的是,搜索模型抱怨以下几行,但是如果没有这些行,一切似乎都可以按预期工作:

$this->addCondition(...);

对于模型PaymentEvent(表:subs_payment_event),它具有链接到模型Currency的currency_id字段,这是完整的附加代码集(使用基本模板):

在主模型中,PaymentEvent.php:

public function getCurrencyName()
{
    return $this->currency->name;
}

在搜索模型中,PaymentEventSearch.php:

public $currencyName;

在其规则中:

[['currencyName'], 'safe'],

在其setSort语句的属性中,包括:

'currencyName' => [
    'asc' => ['subs_currency.name' => SORT_ASC],
    'desc' => ['subs_currency.name' => SORT_DESC],
    'label' => 'Currency'
],

在网格过滤条件之前:

$query->joinWith(['currency' => function ($q) {
        $q->where('subs_currency.name LIKE "%' . $this->currencyName . '%"');
    }]);

最后,在视图的GridView列数组中(包括我通常的指向相关模型记录的链接):

[
    'attribute' => 'currencyName',
    'label' => 'Currency',
    'format' => 'raw',
    'value' => function ($data) {
            return Html::a($data->currency->name, ['/currency/' . $data->currency_id]);
        },
],