2017-05-27 53 views
0

我有足球比赛功能。但总是在主场或离开时显示相同的球队。YII2 - 如何在同一张表上显示两个关系的不同值

这里是我的代码,

模型[赛事]:

use app\models\Team; 

... 

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

... 
  • 团队模式是所有球队的名单
  • 匹配表,只限于主场球队的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(); ?> 

但结果总是显示客队都在家或外出:

Home : 
    Team Away 
Away : 
    Team Away 

如何解决这一问题?

回答

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`'); 

的你应该指的是列名使用了正确的表的别名

+0

另一个错误:SQLSTATE [42000]:语法错误或访问冲突:1066不是唯一的表/别名:'团队' – Rivaldy

相关问题