【问题标题】:Yii2 Many to Many with Self - filter through grid view (no attribute?)Yii2 Many to Many with Self - 通过网格视图过滤(没有属性?)
【发布时间】:2016-10-27 20:47:20
【问题描述】:

我使用了 Gii AJAX Crud 生成器,但我被自己的愚蠢逼到了墙角。我正在使用 Yii 2 并希望在与连接表中与 ITSELF 有这种关系的表上使用网格视图进行多对多搜索。

table tag (id, name).

table tag_child (parent_id, child_id)


Class Tag
...
public function getParents()
{
    return $this->hasMany(self::className(), ['id' => 'child_id'])
        ->viaTable('tag_child', ['parent_id' => 'id']);
}

public function getChildren()
{
    return $this->hasMany(self::className(), ['id' => 'parent_id'])
        ->viaTable('tag_child', ['child_id' => 'id']);
}

在我的网格视图/columns 中:

    [
    'class' => '\kartik\grid\DataColumn',
    'attribute'=>'name',
],
[
    'class' => '\kartik\grid\DataColumn',
    'label' => 'Tag Type',
    'value' => function($tag) {
        return $tag->displayTagTypes();
    },
    'attribute' => 'tagTypes'
],


 TagQuery.php
 ...
 public $tagTypes;
        public function search($params)
 {
    $query = Tag::find();

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

    $this->load($params);

    if (!$this->validate()) {
        // $query->where('0=1');
        return $dataProvider;
    }

    $query->joinWith('parents p');

    $query->andFilterWhere(['id' => $this->id]);

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

    return $dataProvider;
}

我可以使用该值函数在索引表中显示结果,但我的标签过滤器无​​法按标签类型进行搜索。我该如何填充?

作为一个例子,当它不是多对多时,我可以使用将我的属性设置为'joinedTableName.value',并且只要我添加一个 $query->orFilterWhere('like', 'parent.name' , $this->id) 或其他。但是我现在很茫然……

【问题讨论】:

    标签: php mysql yii yii2 many-to-many


    【解决方案1】:

    在控制器中声明 $searchModel = new TagQuery(),然后将 $searchModel 传递给视图并将其作为 'filterModel' => $searchModel 包含在 GridView 选项中。

    要么这样,要么您可以使用特定的过滤器类型和每列的过滤器逻辑进行真正的自定义过滤器。

    您在查询模型中声明了 public tagType,但您不使用它做任何事情。 $query->andFilterWhere(['like', 'tag.name', $this->tagType]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多