Linking same table with two foreign keys in cakephp 3

痞子三分冷 提交于 2019-12-23 21:16:34

问题


I have a table match_schedules which stores matches between two teams. There is table teams to store team information.

Columns of match_schedules are

+-----+---------+---------+-------+-------+
| id  | team_a  | team_b  | date  | venue |
+-----+---------+---------+-------+-------+

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.

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

I have tried this In TeamsTable.php

$this->belongsTo('MatchSchedules', [
    'foreignKey' => 'team_a',
    'joinType' => 'INNER'
]);
$this->belongsTo('MatchSchedules', [
    'foreignKey' => 'team_b',
    'joinType' => 'INNER'
]);

In MatchSchedulesTable.php

$this->hasMany('Teams', [
    'foreignKey' => 'team_a'
]);
$this->hasMany('Teams', [
    'foreignKey' => 'team_b'
]);

But this is not working.


回答1:


You did not properly set up associations

TeamsTable.php

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

In MatchSchedulesTable.php

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

and

$matches = $this->MatchSchedules->find('all', [
  'contain' => [
      'TeamsA',
      'TeamsB
  ]
]);

Is nice to be if you rename:

MatchSchedulesA to HomeMatches 
MatchSchedulesB to GuestMatches 
team_a to home_team 
team_b to guest_team 
TeamsA to HomeTeams 
TeamsB to GuestTeams 


来源:https://stackoverflow.com/questions/39086686/linking-same-table-with-two-foreign-keys-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!