gpt4 book ai didi

cakephp - 在 cakephp 3 中用两个外键链接同一个表

转载 作者:行者123 更新时间:2023-12-04 14:38:12 24 4
gpt4 key购买 nike

我有一张 table match_schedules存储两个 teams 之间的匹配.有 table teams存储团队信息。
match_schedules的栏目是

+-----+---------+---------+-------+-------+
| 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'
]);

在 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 - 在 cakephp 3 中用两个外键链接同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com