dongxi1943 2016-10-27 20:47
浏览 63
已采纳

Yii2有多个自我 - 通过网格视图过滤(没有属性?)

I've used the Gii AJAX Crud generator, and I'm being driven up a wall by my own stupidity. I am using Yii 2 and want to search with many to many, on a table that has that relation with ITSELF in a junction table, with the Grid View.

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']);
}

And in my grid-view /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;
}

I'm able to display the results in my index table with that value function, but my Tag filter isn't able to search by tagTypes. How do I populate that?

As an example, when it's not many to many, I can use set my attribute to 'joinedTableName.value' and it works as soon as I add a $query->orFilterWhere('like', 'parent.name', $this->id) or whatever. But I'm at a loss now...

  • 写回答

1条回答 默认 最新

  • doucu7330 2016-10-29 13:31
    关注

    Declare $searchModel = new TagQuery() in your controller, then pass the $searchModel to the view and include it in the GridView options as 'filterModel' => $searchModel.

    Either that, or you can do really custom filters using specific filterTypes and filter logic for each column.

    You declare public tagType in the query model, but you don't do anything with it. $query->andFilterWhere(['like', 'tag.name', $this->tagType]);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制