关联困难

时间:2014-07-08 04:26:38

标签: cakephp associations models

我目前有一些型号。协会如下:

  • 日程安排有多次匹配
  • 活动有多个时间表
  • 活动有很多分部
  • TeamEvent有很多比赛(两个,客场和主场)
  • Team hasMany TeamEvent(将实际团队与部门联系起来)
  • Division hasMany TeamEvent

我试图找到每个TeamEvent的所有匹配项。

$this->TeamEvent->find('all', array('conditions' => array('TeamEvent.team_id' => $this->Team->id)));

问题是所有匹配都被放入具有id 1的TeamEvent。

这是相关的SQL:

SELECT `Match`.`id`, `Match`.`schedule_id`, `Match`.`event_id`, `Match`.`home_team_id`, `Match`.`away_team_id`, `Match`.`home_result`, `Match`.`away_result`, `Match`.`matchtime`, `Schedule`.`id`, `Schedule`.`week`, `Schedule`.`map_name`, `Schedule`.`start_date`, `Schedule`.`end_date`, `Schedule`.`event_id`, `HomeTeam`.`id`, `HomeTeam`.`division_id`, `HomeTeam`.`team_id`, `HomeTeam`.`active`, `HomeTeam`.`win`, `HomeTeam`.`loss`, `AwayTeam`.`id`, `AwayTeam`.`division_id`, `AwayTeam`.`team_id`, `AwayTeam`.`active`, `AwayTeam`.`win`, `AwayTeam`.`loss` FROM `openplay`.`matches` AS `Match` LEFT JOIN `openplay`.`schedules` AS `Schedule` ON (`Match`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `openplay`.`team_events` AS `HomeTeam` ON (`Match`.`home_team_id` = `HomeTeam`.`id`) LEFT JOIN `openplay`.`team_events` AS `AwayTeam` ON (`Match`.`away_team_id` = `AwayTeam`.`id`) WHERE ((`HomeTeam`.`team_id` = 1) OR (`AwayTeam`.`team_id` = 1)) ORDER BY `Match`.`matchtime` desc LIMIT 1

如您所见,唯一的条件是Away和Home TeamEvent。我该怎么做才能检查Schedule?

1 个答案:

答案 0 :(得分:1)

$this->Team->id

这保存了当前指向团队模型的指针 - 除非你知道自己在做什么,否则我不建议使用它。我建议你在函数调用中使用一个参数:

public function something($team_id) {
    $matches = $this->TeamEvent->find('all', array('conditions' => array('TeamEvent.team_id' => $team_id)));
//etc

}