Yii2如何设置Relation Alias

Jør*_*gen 2 yii2

我有一个带有"父"列的类别表,该列引用同一个表.当我尝试更新GridView以显示父类别名称而不是类别父ID时,这给了我一些麻烦.

如何在yii2中定义关系别名?

Jør*_*gen 5

解决了:

我在CategorySearch模型中添加了别名:它与关系getParentCategory()连接,并为其命名parentCategory作为'category'表的别名.

public function search($params)
{
    $query = Category::find();

    $query->joinWith(['createdBy'])->joinWith(['parentCategory' => function($query) { $query->from(['parentCategory' => 'category']); }]);

    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'user.username', $this->created_by])
        ->andFilterWhere(['like', 'parentCategory.name', $this->parent]);
Run Code Online (Sandbox Code Playgroud)