开发者

CakePHP Model Relationship with Multiple Foreign Keys

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'开发者_如何学C),
  '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


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


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__$}')
            )
        ),
    )
);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜