2016-08-22 65 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