Yii2 - 获得多个表格

时间:2016-03-10 18:02:20

标签: yii yii2

我需要加入5个表才能获得团队的所有用户。表格是:

User: iduser | firstName | lastName
Team: idteam | name
TeamUser: idteamuser | idteam | iduser
Portal: idportal | name
PortalTeam: idportalteam | idteam

门户模型中,我需要获取该门户的所有用户。这可能吗?

2 个答案:

答案 0 :(得分:2)

我认为Portal Model中存在一个缺少字段(idportalteam)以链接到其他模型。添加后,您可以为所有模型创建关系。

门户:

public function getPortalTeam()
{
    return $this->hasOne(PortalTeam::className(), ['idportalteam' => 'idportalteam']);
}

PortalTeam:

public function getTeamUser()
{
    return $this->hasOne(TeamUser::className(), ['idteam' => 'idteam']);
}

TeamUser:

public function getTeam()
{
    return $this->hasOne(Team::className(), ['idteam' => 'idteam']);
}

TeamUser:

public function getUser()
{
    return $this->hasOne(User::className(), ['iduser' => 'iduser']);
}

要从Portal使用获取模型:

$portal = (new Portal())->findOne(xyz);
$team = (($portal->portalTeam)->teamUser)->team;
$user = (($portal->portalTeam)->teamUser)->user;

答案 1 :(得分:0)

不是-best-答案,但可以使用ActiveQuery对象和join()方法。 http://www.yiiframework.com/doc-2.0/yii-db-query.html#join()-detail

经验:

$data = \Portal::find()
    ->join($type, $table, $on = '', $params = [])
->andWhere([/* ... */])
->all();