In Yii2, how do I join a table for myself?

I have a page table. Pages can have parents, which are also pages. I want to select all pages with parent_id = NULL and their "children". But when I try it

public function getPages() { return $this->hasMany(Page::className(), ['parent_id' => 'id']); } 

I get 1066 Not a unique table / alias: "page" error ... I know how to fix this in Yii1, but I can't figure out how to fix it in Yii2.

+5
source share
2 answers

I did this for the grades module in which I have parent-child relationships for classes.

Follow these steps:

  • In this model file, write this code for self-attachment. We need a table name alias. Here "parent" is an alias.

     public function getParent() { return $this->hasOne(self::classname(), ['id' => 'parent_id'])-> from(self::tableName() . ' AS parent'); } 
  • Write this code in your view file

     [ 'label' => 'Parent Grade', 'value' => ($model->parent_id != '' || $model->parent_id != 0) ? $model->parent->name : 'Root Grade', ], 

Here, in my code, if the parent_id field parent_id not null / zero, it displays the parent name of the class otherwise "Root Grade".

+3
source

You need a table name alias.

  $this->hasMany(Category::className(), ['parent_id' => 'id'])->from(['cat' => 'category']); 

See discussion here .

+2
source

All Articles