在cakephp 3中用两个外键链接同一张表 [英] Linking same table with two foreign keys in cakephp 3
本文介绍了在cakephp 3中用两个外键链接同一张表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张表格 match_schedules
,其中存储了两个 teams
之间的比赛。有表 teams
来存储团队信息。
I have a table match_schedules
which stores matches between two teams
. There is table teams
to store team information.
比赛时间表$ c的列$ c>是
+-----+---------+---------+-------+-------+
| id | team_a | team_b | date | venue |
+-----+---------+---------+-------+-------+
因为我有两列 team_a
和 team_b
引用 teams
表,我不能使用 team_id
作为外键这两个列。
Since I have two columns team_a
and team_b
referencing teams
table, I can't use team_id
as foreign key in both columns.
现在,我想将这两列与 teams
表关联,以便我可以轻松地检索关联的数据
Now, I want to associate these two columns with teams
table so that I can easily retrieve associated data like
$matches = $this->MatchSchedules->find('all', [
'contain' => [
'Teams'
]
]);
我已经在TeamsTable.php 中尝试过此
I have tried this In 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
这篇关于在cakephp 3中用两个外键链接同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文