简体   繁体   English

Kohana ORM(自定义查询)与MySQL ORDER BY和GROUP BY

[英]Kohana ORM (custom query) vs MySQL ORDER BY & GROUP BY

I have a table with messages. 我有一张桌子,上面有消息。 I want to group these messages into conversations, checking if there is unread messages and previewing the latest message. 我想将这些消息分组为对话,检查是否有未读消息并预览最新消息。

My current ORM looks like this: 我当前的ORM如下所示:

$text = new Model_Text;
$text->select(DB::expr('min(`text`.`read`) AS `read_all`'))
->where('time', '>', $time_offset);
->order_by('read', 'DESC')->order_by('time', 'ASC')
->group_by('contact')->with('user')->find_all();

But as you know MySQL groups before it orders, meaning I don't get the latest message, while the min('text'.'read') trick makes sure I always know if the conversation has unread messages. 但是,正如您所知,MySQL在订购之前会进行分组,这意味着我没有收到最新消息,而min('text'.'read')技巧可确保我始终知道对话中是否有未读消息。

To get the latest message in each conversation, I would do a MySQL query like this: 为了在每次对话中获取最新消息,我将执行以下MySQL查询:

SELECT min(q1.`read`) as read_all, q2.* FROM texts q1 
INNER JOIN (
    SELECT * FROM texts ORDER BY time DESC
) q2 ON(q1.contact = q2.contact) 
GROUP BY q1.contact 
ORDER BY q2.`time` DESC, q2.`read` ASC

But I am completely lost as for how to optimally implement this query with ORM. 但是我完全不知道如何使用ORM最佳实现此查询。

My best guess would be to execute the above query directly with Kohana's DB class and load an ORM object for each row returned. 我最好的猜测是直接使用Kohana的DB类执行上述查询,并为返回的每一行加载一个ORM对象。 But, this will cause one database hit for each and every conversation loaded into ORM, for data that I already retrieved - stupid! 但是,这将导致对于每个已加载到ORM中的会话的数据库命中,这对于我已经检索到的数据是很愚蠢的!

Let me know your thoughts! 让我知道你的想法!

Thanks. 谢谢。

There is not a good way to do this with the ORM class, even if you could select the data properly, you wouldn't be able to read it back, as your Model_Text won't have the read_all property. 即使您可以正确选择数据,也无法通过ORM类来执行此操作,因为Model_Text将没有read_all属性,因此您将无法读取数据。

I think the best way to do this is with two queries, The first would be to get the conversations that you are interested in, select contact, min(read) as read_all ... where time > $time_offset and group by contact . 我认为最好的方法是通过两个查询,第一个是获取您感兴趣的对话, select contact, min(read) as read_all ... where time > $time_offset并按group by contact Once you have the contact and read_all, you can make another query the get just the latest text for each conversation and load that into your Model_Text as suggested by Carl: DB::query(DATABASE::SELECT, $sql)->as_object('Model_Text')->execute() 获得联系信息和read_all后,您可以进行另一个查询,以获取每次对话的最新文本,然后按照Carl的建议将其加载到Model_Text中: DB::query(DATABASE::SELECT, $sql)->as_object('Model_Text')->execute()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM