按外键字段过滤

Filter by a field that's a foreign key

使用 Yii2.

我有一个名为 'calificacion' 的 table,它有一个外键 'alumno-id',指向 table 校友中的字段 ID。

GridView 小部件中定义的列是:

        [
            'header' => 'Alumno',
            'attribute' => 'alumno.id',
            'value' => 'alumno.name'
        ],

它显示得很好,但是 header 列中的过滤器没有出现。我想要一个文本框来写校友的名字并进行过滤。我怎样才能做到这一点?

编辑:这是文件https://dl.dropboxusercontent.com/u/7059378/Desktop.zip

您必须首先在 table 'calificacion' 的模型中定义一个关系,例如

public function getAlumno()
{
    return $this->hasOne(Alumno::className(), ['id' => 'alumno_id']);
}

比在验证后加入 tables 的 Calificacion 集的搜索模型,例如

$query->joinWith('alumno');

比设置搜索喜欢

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

首先在您的 SearchModel 中声明一个属性。

public $alumno_name;

在您的搜索模型的规则中添加:

[['alumno_name'], 'safe'],

在搜索方法中加入 alumno 关系(假设您的 Calificacion 模型中存在 alumno 关系):

$query = Calificacion::find()
    ->joinWith(['alumno alumno']);

要使用 $alumno_name 排序,请添加:

$dataProvider->sort = [
    'attributes' => [

        //Other attributes here

        'alumno_name' => [
            'asc' => ['alumno.name' => SORT_ASC],
            'desc' => ['alumno.name' => SORT_DESC],
        ],
    ]
];

要过滤此内容,您必须添加:

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

最后在您的网格视图中添加:

[
    'attribute' => 'alumno_name',
    'value' => 'alumno.name'
],

您可以找到更多信息 here and here

也可以使用 'label' => 'Alumno'.

而不是 header