【问题标题】:Filter setup for related model in GridViewGridView 中相关模型的过滤器设置
【发布时间】:2015-02-02 19:17:51
【问题描述】:

我正在尝试在 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',

            ],

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

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

【问题讨论】:

  • 你能把完整的php代码贴在“ServiceChargeSearch.php”中吗?该错误是由于验证器配置不正确
  • @BalajiViswanath - 更新并添加了 serviceChargeSearch.php 的完整代码

标签: php gridview yii yii2


【解决方案1】:

其实它比看起来要简单得多。

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

  2. 使用查询添加连接 - 比如 - $query-&gt;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 你还应该将关系名称设置为public $roomCategory

就是这样。相关表的排序和过滤都可以完美运行。

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

最新版本更新:

  • 不需要添加公共 $ 属性。
  • 也不需要为关系添加安全属性。
  • 但是你当前模型中的属性,你想要过滤的是 添加到必须的安全属性中。
  • 最重要的是,在您的网格视图中,相关属性必须 采用闭包格式。

就是例子

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

请记住,您使用的 relation_name.related_table_attribute_name 过滤器对我不起作用。

【讨论】:

    【解决方案2】:

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

    $this->addCondition(...);
    

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

    在主模型中,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]);
            },
    ],
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多