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_a
和team_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)
但这不起作用.
您没有正确设置关联
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)