Yii2如何设置Relation Alias

时间:2015-03-09 19:14:37

标签: yii2

我有一个带有父母'的分类表。引用同一个表的列。当我试图更新GridView以显示父类别名称而不是类别父ID时,这给我带来了一些麻烦。

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

2 个答案:

答案 0 :(得分: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]);

答案 1 :(得分:1)

这是我的代码。

/models/CategorySearch.php

$params['id'] = (int)$params['id'];
$query = Category::find()->where(['root' => $params['id']]);

字段root这是您的字段parent。    

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Category;

/**
 * CategorySearch represents the model behind the search form about `app\models\Category`.
 */
class CategorySearch extends Category
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'rank'], 'integer'],
            [['name', 'description'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $params['id'] = (int)$params['id'];
        $query = Category::find()->where(['root' => $params['id']]);

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

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

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

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

        return $dataProvider;
    }
}

控制器:

public function actionIndex()
    {
        $searchModel = new CategorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }