使用类似这样的查询:
SELECT * FROM (
SELECT * FROM message ORDER BY added_on DESC
) as m WHERE receiver_id = 2 GROUP BY sender_id ORDER BY priority_id DESC;
我知道如何使用findAllBySql
执行此操作:
$this->findAllBySql(
'SELECT * FROM (
SELECT * FROM message ORDER BY added_on DESC
) as m WHERE receiver_id = :receiverId
GROUP BY sender_id
ORDER BY priority_id DESC',
array('receiverId' => $userId));
但是我想知道是否有任何方法可以使用CDbCriteria执行此操作,因为以下代码当然不起作用:
$criteria = new CDbCriteria();
$criteria->condition = 'receiver_id = :receiverId';
$criteria->group = 'sender_id';
$criteria->order = 'priority_id DESC, added_on DESC';
$criteria->params = array('receiverId' => $userId);
感谢。
答案 0 :(得分:11)
我知道为时已晚。我有类似的问题,我试着像这样接近
$criteria = new CDbCriteria();
$criteria->select = '*, MAX(added_on) max_added_on';
$criteria->condition = 'receiver_id = :receiverId';
$criteria->group = 'sender_id';
$criteria->order = 'priority_id DESC, max_added_on DESC';
$criteria->params = array('receiverId' => $userId);
它解决了我的问题。如果要检索max_added_on,只需在模型类上添加另一个属性。
答案 1 :(得分:6)
如果你有一个相当复杂的SQL查询,最好将它保存在SQL中,而不是在Active Record中编写它。是的,它限制了数据库的可移植性,但是您可能没有这些查询,并且更简单,更易维护的代码总是获胜。