在cakephp 3中将同一个表与两个外键相关联

Anu*_*TBE 2 cakephp model-associations cakephp-3.2

我有一张表match_schedules存储两个之间的匹配teams.有表teams存储团队信息.

match_schedules

+-----+---------+---------+-------+-------+
| id  | team_a  | team_b  | date  | venue |
+-----+---------+---------+-------+-------+
Run Code Online (Sandbox Code Playgroud)

由于我有两列team_ateam_b引用teams表,我不能team_id在两列中使用外键.

现在,我想将这两列与teams表关联起来,以便我可以轻松地检索关联的数据

$matches = $this->MatchSchedules->find('all', [
  'contain' => [
      'Teams'
  ]
]);
Run Code Online (Sandbox Code Playgroud)

在TeamsTable.php中试过这个

$this->belongsTo('MatchSchedules', [
    'foreignKey' => 'team_a',
    'joinType' => 'INNER'
]);
$this->belongsTo('MatchSchedules', [
    'foreignKey' => 'team_b',
    'joinType' => 'INNER'
]);
Run Code Online (Sandbox Code Playgroud)

在MatchSchedulesTable.php中

$this->hasMany('Teams', [
    'foreignKey' => 'team_a'
]);
$this->hasMany('Teams', [
    'foreignKey' => 'team_b'
]);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

Sal*_*nes 6

您没有正确设置关联

TeamsTable.php

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

在MatchSchedulesTable.php中

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

$matches = $this->MatchSchedules->find('all', [
  'contain' => [
      'TeamsA',
      'TeamsB
  ]
]);
Run Code Online (Sandbox Code Playgroud)

很高兴如果你重命名:

MatchSchedulesA to HomeMatches 
MatchSchedulesB to GuestMatches 
team_a to home_team 
team_b to guest_team 
TeamsA to HomeTeams 
TeamsB to GuestTeams 
Run Code Online (Sandbox Code Playgroud)