YII2 - 如何在同一个表上显示两个关系的不同值

时间:2017-05-27 07:05:45

标签: php sql yii2 yii2-basic-app

我有足球比赛功能。但总是在家里或外面展示相同的团队。

这是我的代码,

模特[匹配]:

use app\models\Team;

...

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

...
  • 团队模型是所有团队的列表
  • 匹配表仅保留Home Field和Away Field上的Team的ID

模型[MatchSearch]:

....

    public $team_home;
    public $team_away;

    public function rules()
    {
        return [
            [['home', 'away'], 'integer'],
            [['team_home', 'team_away'], 'safe'],
        ];
    }

    ...

    public function search($params)
    {
        $query = Match::find()->joinWith(['team']);

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

        $dataProvider->sort->attributes['team_home'] = [
            'asc' => ['team.team' => SORT_ASC],
            'desc' => ['team.team' => SORT_DESC],
        ];

        $dataProvider->sort->attributes['team_away'] = [
            'asc' => ['team.team' => SORT_ASC],
            'desc' => ['team.team' => SORT_DESC],
        ];

        $this->load($params);

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

        $query->andFilterWhere([
            'home' => $this->home,
            'away' => $this->away,
        ]);

        $query->andFilterWhere(['like', 'team.team', $this->team_home])
              ->andFilterWhere(['like', 'team.team', $this->team_away]);

        return $dataProvider;
    }

观点[索引]:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'attribute' => 'home',
            'value' => function($data) {
                return $data->team->team;
            },
        ],
        [
            'attribute' => 'away',
            'value' => function($data) {
                return $data->team->team;
            },
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
<?php Pjax::end(); ?>

但结果总是显示Away队的主场或客场:

Home :
  Team Away
Away :
  Team Away

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用内部联接

 $query = Match::find()
      ->innerJoin('team_tname as home', '`team_taame`.`id` = `match_table_name`.`home`')
      ->innerJoin('team_taname as away', '`team_name`.`id` = `match_table_name`.`away`');

您应该使用正确的表别名

来引用列名称