PHP,Yii2 GridView过滤关系值

时间:2014-02-24 16:01:25

标签: php entity-relationship yii2

继续之后:

Yii2 how does search() in SearchModel work?

我希望能够过滤GridView列关系数据。这就是我的意思:

我有两个表,TableATableB。两者都有使用Gii生成的相应模型。 TableA有一个TableB值的外键,如下所示:

TableA
attrA1, attrA2, attrA3, TableB.attrB1

TableB
attrB1, attrB2, attrB3

attrA1和attrB1是其相应表的主键。

现在,我有GridView attrA2attrA3attrB2的Yii2。我在attrA2attrA3上有一个工作过滤器,以便我可以搜索列值。我也对这两个列进行了工作排序 - 只需单击列标题即可。我希望能够在attrB2上添加此过滤和排序。

我的TableASearch模型如下所示:

public function search($params){
    $query = TableA::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $this->addCondition($query, 'attrA2');
    $this->addCondition($query, 'attrA2', true);
    $this->addCondition($query, 'attrA3');
    $this->addCondition($query, 'attrA3', true);

    return $dataProvider;
}

在我的TableA模型中,我设置了相关的值

    public $relationalValue;

public function afterFind(){
    $b = TableB::find(['attrB1' => $this->attrB1]);
    $this->relationalValue = $b->relationalValue;
}

虽然这可能不是最好的方法。我想我必须在我的搜索功能中使用$ relationalValue,但我不确定如何。同样,我希望能够按照此列进行排序 - 就像我可以通过点击标题链接一样attrA2AttrA3。任何帮助,将不胜感激。感谢。

3 个答案:

答案 0 :(得分:18)

这是基于guide中的描述。 SearchModel的基本代码来自Gii代码生成器。这也假设使用hasOne()hasMany()关系设置了$ this-> TableB。请参阅此doc

<强> 1。设置搜索模型

TableASearch模型中添加:

public function attributes()
{
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['TableB.attrB1']);
}

public function rules() 
{
    return [
        /* your other rules */
        [['TableB.attrB1'], 'safe']
    ];
}

然后在TableASearch->search()添加($this->load()之前):

$dataProvider->sort->attributes['TableB.attrB1'] = [
      'asc' => ['TableB.attrB1' => SORT_ASC],
      'desc' => ['TableB.attrB1' => SORT_DESC],
 ];

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

然后实际搜索您的数据($this->load()下方):

$query->andFilterWhere(['like','TableB.attrB1',$this->getAttribute('TableB.attrB1'));

<强> 2。配置GridView

添加到您的视图中:

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        /* Other columns */
       'TableB1.attrB1',
        /* Other columns */        
     ]
]);

答案 1 :(得分:3)

我也遇到了这个问题,我的解决方案也大相径庭。我有两个简单的模型:

图书:

class Book extends ActiveRecord
{
    ....

    public static function tableName()
    {
        return 'books';
    }

    public function getAuthor()
    {
        return $this->hasOne(Author::className(), ['id' => 'author_id']);
    }

作者:

class Author extends ActiveRecord
{

    public static function tableName()
    {
        return 'authors';
    }

    public function getBooks()
    {
        return $this->hasMany(Book::className(), ['author_id' => 'id']);
    }

但我的搜索逻辑是不同的模型。而且我没有找到如何在不创建额外字段author_first_name的情况下实现搜索。所以这是我的解决方案:

class BookSearch extends Model
{
    public $id;
    public $title;
    public $author_first_name;

    public function rules()
    {
        return [
            [['id', 'author_id'], 'integer'],
            [['title', 'author_first_name'], 'safe'],
        ];
    }

    public function search($params)
    {
        $query = Book::find()->joinWith(['author' => function($query) { $query->from(['author' => 'authors']);}]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => array('pageSize' => 50),
            'sort'=>[
                'attributes'=>[
                    'author_first_name'=>[
                        'asc' => ['author.first_name' => SORT_ASC],
                        'desc' => ['author.first_name' => SORT_DESC],
                    ]
                ]
            ]
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }
        ....
        $query->andWhere(['like', 'author.first_name', $this->author_first_name]);
        return $dataProvider;
    }
}

这是用于创建表别名:function($query) { $query->from(['author' => 'authors']);}

GridView代码是:

<?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'attribute' => 'id',
            'filter' => false,
        ],
        [
            'attribute' => 'title',
        ],
        [
            'attribute' => 'author_first_name',
            'value' => function ($model) {
                    if ($model->author) {
                        $model->author->getFullName();
                    } else {
                        return '';
                    }
                },
            'filter' => true,
        ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

我将感谢任何批评和建议。

答案 2 :(得分:3)

在Yii 2.0中,按列过滤网格视图非常容易。请将filter属性添加到具有查找值的gridview列,如下所示:

[
        "class" => yii\grid\DataColumn::className(),
        "attribute" => "status_id",
        'filter' => ArrayHelper::map(Status::find()->orderBy('name')->asArray()->all(), 'id', 'name'),
        "value" => function($model){
            if ($rel = $model->getStatus()->one()) {
                return yii\helpers\Html::a($rel->name,["crud/status/view", 'id' => $rel->id,],["data-pjax"=>0]);
            } else {
                return '';
            }
        },
        "format" => "raw",
],