8
votes

In my CakePHP app I have models for Matches and Teams. Each Match has a home_team_id and an away_team_id, both of which reference a different Team.

In my team.php file, I am able to form the relationship for a Team's 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 retrieve a Team's home and away Matches in a single array. That is, the retrieved Matches are returned in separate HomeMatch and AwayMatch arrays, which causes sorting difficulties.

I have tried the following:

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

...with no luck.

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

Thanks, Ben

3

3 Answers

13
votes

A 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__$}'
    )
);
8
votes

I was having a similar issue and instead of creating a finderQuery I used the conditions operator and it worked 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__$}')
            )
        ),
    )
);
0
votes

They are returned in seperate array's because the sort of represent different models (in this particular case the model is the same).

You should probably build a helper method to go over the retrieved data (in the model object or in a separate helper class) and "flatten" it. then you'd be able to sort it.

Ken.