【问题标题】:CakePHP HABTM find first record which has certain related recordsCakePHP HABTM 查找具有某些相关记录的第一条记录
【发布时间】:2014-05-08 19:45:34
【问题描述】:

我在 GamesParticipants 之间有一个 HABTM 关系。我需要找到一个Game,它有Participants,ID 为12“绑定”到它。如何做到这一点?

我试过了

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

这不起作用,因为 SQL 查询以 WHERE participant_id IN (1, 2) 结束,这不是我想要实现的(它找到第一个 GameParticipant 12不是具有两者的)。有什么建议吗?

【问题讨论】:

    标签: sql cakephp has-and-belongs-to-many


    【解决方案1】:

    为了找到同时包含参与者 #1 和参与者 #2 的游戏,我认为您需要手动加入:

    $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
                  )
              )
         )
     ));
    

    【讨论】:

    • 谢谢。我自己也想到了同样的解决方案,但徒劳地希望 CakePHP 能针对这种情况内置一些东西。
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多