2016-08-22 92 views
1

我有一個表match_schedules,它存儲兩個teams之間的匹配項。有teams表存儲團隊信息。的match_schedules在cakephp 3中鏈接相同的表與兩個外鍵3

列是

+-----+---------+---------+-------+-------+ 
| id | team_a | team_b | date | venue | 
+-----+---------+---------+-------+-------+ 

因爲我有兩列team_ateam_b引用teams表,我不能使用team_id在兩列外鍵。

現在,我想這兩列與teams表,這樣我可以輕鬆檢索喜歡

$matches = $this->MatchSchedules->find('all', [ 
    'contain' => [ 
     'Teams' 
    ] 
]); 

相關數據我已經嘗試了這個 在TeamsTable.php

$this->belongsTo('MatchSchedules', [ 
    'foreignKey' => 'team_a', 
    'joinType' => 'INNER' 
]); 
$this->belongsTo('MatchSchedules', [ 
    'foreignKey' => 'team_b', 
    'joinType' => 'INNER' 
]); 

關聯In MatchSchedulesTable.php

$this->hasMany('Teams', [ 
    'foreignKey' => 'team_a' 
]); 
$this->hasMany('Teams', [ 
    'foreignKey' => 'team_b' 
]); 

但這不起作用。

+0

改變 'MatchSchedules' 到 'MatchSchedulesA' 和 'MatchSchedulesB', '團隊' 到「TeamsA'and 'TeamsB' – Salines

+0

這給'MatchSchedules沒有關聯在'$ matches = $ this-> MatchSchedules-> find('all',['contain'=>'Teams']);' –

+0

this'given'Base table or view not found:1146''team_a'不存在'。 –

回答

4

你沒有正確設置關聯

TeamsTable.php

$this->hasMany('MatchSchedulesA', [ 
    'foreignKey' => 'team_a', 
    'className' => 'MatchSchedules' 
]); 
$this->hasMany('MatchSchedulesB', [ 
    'foreignKey' => 'team_b', 
    'className' => 'MatchSchedules' 
]); 

在MatchSchedulesTable.php

$this->belongsTo('TeamsA', [ 
    'foreignKey' => 'team_a', 
    'joinType' => 'INNER', 
    'className' => 'Teams' 
]); 
$this->belongsTo('TeamsB', [ 
    'foreignKey' => 'team_b', 
    'joinType' => 'INNER', 
    'className' => 'Teams' 
]); 

$matches = $this->MatchSchedules->find('all', [ 
    'contain' => [ 
     'TeamsA', 
     'TeamsB 
    ] 
]); 

是很好,如果您重命名爲:

MatchSchedulesA to HomeMatches 
MatchSchedulesB to GuestMatches 
team_a to home_team 
team_b to guest_team 
TeamsA to HomeTeams 
TeamsB to GuestTeams