如何将多个记录连接到一个表或使用包含条件?

时间:2015-05-06 08:30:05

标签: mysql cakephp join

我正在使用cakePHP 2.6.4 我有两张表AgentChatAgentChatMember AgentChat有许多AgentChatMember
AgentChatMember属于AgentChat

AgentChat有:id, team_id, agent_chat_member_count个字段 AgentChatMemberid, agent_chat_id, user_id个字段。

我希望AgentChatchat_team_id找到agent_chat_member_count
AgentChatMember包含user_id条件。

    $options['contain'] = array('AgentChatMember');
    $options['conditions']['AgentChat.agent_chat_member_count'] = count($user_ids);
    $options['conditions']['AgentChat.chat_team_id'] = $chat_team_id;

    $res = $this->AgentChat->find('first', $options);

$res是:

     'AgentChat' => array(
        'id' => '1',
        'agent_message_count' => '0',
        'agent_chat_member_count' => '2',
        'chat_team_id' => '14',
        'created' => '2015-05-06 09:52:31',
        'updated' => '2015-05-06 09:52:31'
    ),
    'AgentChatMember' => array(
        (int) 0 => array(
            'id' => '1',
            'agent_chat_id' => '1',
            'user_id' => '26',
            'created' => '2015-05-06 09:52:31'
        ),
        (int) 1 => array(
            'id' => '2',
            'agent_chat_id' => '1',
            'user_id' => '21',
            'created' => '2015-05-06 09:52:31'
        )
    )

通过这个,我得到我想要的,除了事实我不能将user_id条件设置为AgentChatMember,如下所示:$options['conditions']['AgentChatMember.user_id'] = $user_ids;

当我使用连接而不是包含时我可以设置user_id条件,但我得到的结果如下:

(int) 0 => array(
        'AgentChat' => array(
            'id' => '1',
            'agent_message_count' => '0',
            'agent_chat_member_count' => '2',
            'chat_team_id' => '14',
            'created' => '2015-05-06 09:52:31',
            'updated' => '2015-05-06 09:52:31'
        ),
        'AgentChatMember' => array(
            'id' => '2',
            'agent_chat_id' => '1',
            'user_id' => '21',
            'created' => '2015-05-06 09:52:31'
        )
    ),
    (int) 1 => array(
        'AgentChat' => array(
            'id' => '1',
            'agent_message_count' => '0',
            'agent_chat_member_count' => '2',
            'chat_team_id' => '14',
            'created' => '2015-05-06 09:52:31',
            'updated' => '2015-05-06 09:52:31'
        ),
        'AgentChatMember' => array(
            'id' => '2',
            'agent_chat_id' => '1',
            'user_id' => '26',
            'created' => '2015-05-06 09:52:31'
        )
    ),
    ...

可以将多个记录连接到一个表中或包含条件吗? 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以传递conditions to the contain: -

bool died

除此之外,你应该在CakePHP中使用camel封装你的变量。请参阅文档中的Coding Standards