CakePHP 2.1 中的 Facebook 点赞对话列表(与分组最大值、子查询、加入相关)
Posted
技术标签:
【中文标题】CakePHP 2.1 中的 Facebook 点赞对话列表(与分组最大值、子查询、加入相关)【英文标题】:Facebook like conversations list in CakePHP 2.1 (Related to group-wise maximum, sub-query, join) 【发布时间】:2012-05-21 11:49:02 【问题描述】:我有以下 mysql 表:
CREATE TABLE IF NOT EXISTS `conversations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1_id` int(11) NOT NULL,
`user2_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user1_id_2` (`user1_id`,`user2_id`)
);
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`conversation_id` int(11) NOT NULL,
`sender_id` int(11) NOT NULL,
`recipient_id` int(11) NOT NULL,
`subject` varchar(64) NOT NULL,
`body` text NOT NULL,
`created` datetime DEFAULT NULL,
`is_deleted_by_sender` tinyint(3) unsigned NOT NULL DEFAULT '0',
`is_deleted_by_recipient` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
注意:在会话表中 user1_id 小于或等于 user2_id。
我想获取用户 X 的对话列表,其中每个对话由该对话中用户 X 未删除的最后一条消息显示,并对结果进行分页。 (就像 facebook 消息一样。无论最后一条消息是由 X 还是其他用户发送的,都显示为显示消息。
我找到了group-wise maximum solution,它帮助我创建了以下子查询:
SELECT MAX(SubTable.id) AS id, conversation_id
FROM newtravel.messages AS SubTable
WHERE (
((SubTable.sender_id = 9) AND (SubTable.is_deleted_by_sender = 0))
OR
((SubTable.recipient_id = 9) AND (SubTable.is_deleted_by_recipient = 0))
)
GROUP BY conversation_id
我们可以使用这个子查询作为 $this->Paginator->settings 数组中的连接表吗?如果答案是肯定的,它应该生成如下查询:
SELECT m1.id, m1.conversation_id, m1.body, m1.sender_id, m1.recipient_id
FROM messages m1
INNER JOIN ( THE_SUB_QUERY_ABOVE ) m2
ON ( m1.conversation_id = m2.conversation_id
AND m1.id = m2.id )
ORDER BY m1.id DESC
这个最终查询返回想要的结果。但是我想不出在 PaginatorComponent 中设置正确选项的方法。对于这种查询,官方文档是不够的。那么,在这种情况下,我们该如何配置查找条件、连接、子查询等呢?
【问题讨论】:
【参考方案1】:好的。我已经解决了这个问题:
$this->Message->Behaviors->attach('Containable');
$conditionsSubQuery = array(
'OR' => array(
array(
'SubTable.sender_id' => $this->Auth->user('id'),
'SubTable.is_deleted_by_sender' => 0
),
array(
'SubTable.recipient_id' => $this->Auth->user('id'),
'SubTable.is_deleted_by_recipient' => 0
)
)
);
$db = $this->Message->getDataSource();
$subQuery = $db->buildStatement(
array(
'fields' => array('MAX(id)'),
'table' => $db->fullTableName($this->Message),
'alias' => 'SubTable',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQuery,
'order' => null,
'group' => 'conversation_id',
), $this->Message
);
$subQuery = ' Message.id IN (' . $subQuery . ') ';
$this->Paginator->settings = array(
'Message' => array(
'limit' => 5,
'maxLimit' => 5,
'contain' => array(
'Sender' => array(
'id', 'name', 'is_online', 'profile_image', 'thumbnail'
),
'Recipient' => array(
'id', 'name', 'is_online', 'profile_image', 'thumbnail'
),
'Conversation'
),
'order' => 'Message.id DESC'
)
);
$this->set('conversations', $this->Paginator->paginate('Message', $subQuery));
注意“Message”属于“Sender”和“Recipient”,它们是“users”表的别名。
【讨论】:
以上是关于CakePHP 2.1 中的 Facebook 点赞对话列表(与分组最大值、子查询、加入相关)的主要内容,如果未能解决你的问题,请参考以下文章