0

I have a HABTM relation between Games and Participants. I need to find a Game which has Participants with IDs 1 and 2 "bound" to it. How to achieve this?

I tried with

$options['conditions']['participant_id'] = array('1', '2');
$game = $this->GamesParticipant->find('first', $options);

Which does not work, because the SQL query ends up with a WHERE participant_id IN (1, 2) and this is not what I'm trying to achieve (it finds the first Game with either Participant 1 or 2 not one which has both). Any advice?

Oliver
  • 3,981
  • 2
  • 21
  • 35

1 Answers1

0

In order to find games that have both participant #1 and participant #2, I'm thinking you'll need to do a manual join:

$this->GamesParticipant->find('first',
 array(
    'conditions' => array('participant_id' => 1),
    'joins' => array(
          array(
              'table' => 'games_participants',
              'type' => 'inner',
              'alias' => 'GamesParticipant2',
              'conditions' => array(
                   'GamesParticipant.game_id = GamesParticipant2.game_id',
                   'GamesParticipant2.participant_id' => 2
              )
          )
     )
 ));
Kai
  • 3,803
  • 1
  • 16
  • 33
  • Thanks. I thought of the same solution myself, but was vainly hoping that there was something built in CakePHP for this kind of situation. – Oliver May 09 '14 at 08:47