CakePHP model relation to multiple foreign keys

In my CakePHP application, I have models for matches and teams. Each match has home_team_id and away_team_id, both of which refer to another team.

In my team.php file, I can create relationships for team home matches:

var $hasMany = array( 'HomeMatch' => array('className' => 'Match', 'foreignKey' => 'home_team_id'), 'AwayMatch' => array('className' => 'Match', 'foreignKey' => 'away_team_id') ); 

My problem is that I cannot automatically receive commands home and in a match in one array. That is, the matches found are returned to separate arrays HomeMatch and AwayMatch, which causes difficulties in sorting.

I tried the following:

 var $hasMany = array( 'Match' => array('foreignKey' => array('home_team_id', 'away_team_id')) ); 

... no luck.

Any ideas on how to combine these two foreign keys into one relationship?

Thanks Ben

+8
cakephp foreign-keys relationship has-many
source share
3 answers

Custom finderQuery should do the trick:

 public $hasMany = array( 'Match' => array( 'className' => 'Match', 'foreignKey' => false, 'finderQuery' => 'SELECT * FROM `matches` as `Match` WHERE `Match`.`home_team_id` = {$__cakeID__$} OR `Match`.`away_team_id` = {$__cakeID__$}' ) ); 
+13
source share

I had a similar problem and instead of creating finderQuery I used the conditions statement and it works great!

 public $hasMany = array( 'Match' => array( 'className' => 'Match', 'foreignKey' => false, 'conditions' => array( 'OR' => array( array('Match.home_team_id' => '{$__cakeID__$}'), array('Match.away_team_id' => '{$__cakeID__$}') ) ), ) ); 
+8
source share

They are returned in a separate array, because the view represents different models (in this case, the model is the same).

You should probably create a helper method to search for the received data (in the model object or in a separate helper class) and smooth it out. then you can sort it.

Ken

0
source share

All Articles