簡體   English   中英

YII2-如何在同一張表上顯示兩個關系的不同值

[英]YII2 - How to Display Defferent Value of Two Relation on Same Table

我有足球比賽功能。 但是,無論在家還是在外,總是要顯示同一支球隊。

這是我的代碼,

型號[比賽]:

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

如何解決這個問題?

您可以使用內部聯接

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

您應該使用適當的表別名來引用列名

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM