我正在使用 cakePHP 2.6.4。
我有两个表 AgentChat
和 AgentChatMember
。
AgentChat
有许多AgentChatMember
,
AgentChatMember
属于AgentChat
。
AgentChat
具有:id、team_id、agent_chat_member_count
字段。
AgentChatMember
具有:id、agent_chat_id、user_id
字段。
我想通过 chat_team_id
和 agent_chat_member_count
找到 AgentChat
,
和 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'
)
),
...
是否可以将多条记录合并到一个表中或包含条件?
我怎样才能做到这一点?
最佳答案
你可以通过 conditions to the contain :-
$res = $this->AgentChat->find(
'first',
array(
'contain' => array(
'AgentChatMember' => array(
'conditions' => array(
'AgentChatMember.user_id' => $userIds
)
)
),
'conditions' => array(
'AgentChat.agent_chat_member_count' => count($userIds),
'AgentChat.chat_team_id' => $chatTeamId
)
)
);
顺便说一句,您真的应该在 CakePHP 中对变量进行驼峰式封装。查看Coding Standards在文档中。
关于mysql - 如何让多条记录加入一张表或使用contain with conditions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30071398/