在 cakephp 3 中用两个外键链接相同的 table
Linking same table with two foreign keys in cakephp 3
我有一个 table match_schedules
存储两个 teams
之间的匹配项。有tableteams
存储队伍信息
match_schedules
的列是
+-----+---------+---------+-------+-------+
| id | team_a | team_b | date | venue |
+-----+---------+---------+-------+-------+
因为我有两列 team_a
和 team_b
引用 teams
table,我不能在这两列中使用 team_id
作为外键。
现在,我想将这两列与 teams
table 相关联,以便我可以轻松检索相关数据,例如
$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'
]);
在MatchSchedulesTable.php
$this->hasMany('Teams', [
'foreignKey' => 'team_a'
]);
$this->hasMany('Teams', [
'foreignKey' => 'team_b'
]);
但这不起作用。
您没有正确设置关联
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
我有一个 table match_schedules
存储两个 teams
之间的匹配项。有tableteams
存储队伍信息
match_schedules
的列是
+-----+---------+---------+-------+-------+
| id | team_a | team_b | date | venue |
+-----+---------+---------+-------+-------+
因为我有两列 team_a
和 team_b
引用 teams
table,我不能在这两列中使用 team_id
作为外键。
现在,我想将这两列与 teams
table 相关联,以便我可以轻松检索相关数据,例如
$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'
]);
在MatchSchedulesTable.php
$this->hasMany('Teams', [
'foreignKey' => 'team_a'
]);
$this->hasMany('Teams', [
'foreignKey' => 'team_b'
]);
但这不起作用。
您没有正确设置关联
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