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的名字稱爲組