2016-11-12 94 views
2

我有三个表如何从yii2中的许多关系表中获取数据?

---------- 
mysql> show columns from employee; 
+-----------+------------------+------+-----+---------+----------------+ 
| Field  | Type    | Null | Key | Default | Extra   | 
+-----------+------------------+------+-----+---------+----------------+ 
| id  | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| firstname | varchar(30)  | NO |  | NULL |    | 
| lastname | varchar(30)  | YES |  | NULL |    | 
| position | tinyint(1)  | NO |  | 0  |    | 
| email  | varchar(50)  | NO |  | NULL |    | 
+-----------+------------------+------+-----+---------+----------------+ 
5 rows in set (0.00 sec) 

mysql> show columns from groups; 
+---------------+------------------+------+-----+---------+----------------+ 
| Field   | Type    | Null | Key | Default | Extra   | 
+---------------+------------------+------+-----+---------+----------------+ 
| id   | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| name_of_group | varchar(50)  | NO |  | NULL |    | 
+---------------+------------------+------+-----+---------+----------------+ 
2 rows in set (0.00 sec) 
mysql> show columns from groups_of_employee;                 
+-------------+------------------+------+-----+---------+----------------+           
| Field  | Type    | Null | Key | Default | Extra   |           
+-------------+------------------+------+-----+---------+----------------+           
| id   | int(10) unsigned | NO | PRI | NULL | auto_increment |           
| employee_id | int(10) unsigned | NO | MUL | NULL |    |   
| group_id | int(10) unsigned | NO | MUL | NULL |    |           
+-------------+------------------+------+-----+---------+----------------+ 
3 rows in set (0.00 sec) 

和例如一些代码

class employee 
public function getGroupsOfEmployee() 
{ 
    return $this->hasMany(GroupsOfEmployee::className(), ['id' => 
                 'group_id']); 
} 
/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getGroups() 
{ 
    return $this->hasMany(Groups::className(), ['employee_id' => 'id']) 
             ->via('groupsOfEmployee'); 
      //->viaTable('groups_of_employee', ['group_id' => 'id']); 
} 

class groups 
public function getGroupsOfEmployee() 
{ 
    return $this->hasMany(GroupsOfEmployee::className(), 
             ['employee_id' => 'id']); 
} 

我得到

$model = Employee::findOne(1); 
    var_dump($model->getGroups()); 

,但我看不到任何方式如何从表grooup的名字称为组

回答

1

如果关系基于getGroup

你应该使用

$model = Employee::findOne(1); 

    var_dump($model->groups); 
    var_dump($model->groupOfEmployee); 

和访问的值

var_dump($model->groups->id); 
    var_dump($model->groupOfEmployee->id); 
相关问题