我有这个查询(工作正常)。
$sql = 'select * from ps_message p1 INNER JOIN (SELECT MAX(p2.id) as max_id FROM ps_message p2 GROUP BY p2.thread_id) as max_table on p1.id = max_table.max_id';
我想将它转换为我的Symfony2项目。
我尝试使用createQueryBuilder()和使用ResultSetMapping()/ ResultSetMappingBuilder()的Native Query构建DQL查询,但尚未成功。
P.S。使用ResultSetMapping(),我无法使关系字段起作用。我尝试过修改addJoinedEntityResult()等等。:
$rsm = new ResultSetMapping();
$rsm->addEntityResult('BaseBundle:PsMessage', 'p1');
$rsm->addFieldResult('p1', 'id', 'id');
$rsm->addFieldResult('p1', 'message_text', 'messageText');
$rsm->addFieldResult('p1', 'message_type', 'messageType');
$rsm->addFieldResult('p1', 'receiver_message_status', 'receiverMessageStatus');
$rsm->addFieldResult('p1', 'sender_message_status', 'senderMessageStatus');
$rsm->addFieldResult('p1', 'created_date', 'createdDate');
$rsm->addFieldResult('p1', 'modified_date', 'modifiedDate');
$rsm->addFieldResult('t1', 'thread_id', 'thread_id'); //Error
$rsm->addFieldResult('u', 'sender_id', 'sender'); //Error
$rsm->addFieldResult('t', 'thread_id', 'thread'); //Error
$rsm->addFieldResult('p2', 'thread_id', 'thread'); //Error
$sql = 'select * from ps_message p1 INNER JOIN (SELECT MAX(p2.id) as max_id FROM ps_message p2 GROUP BY p2.thread_id) as max_table on p1.id = max_table.max_id';
$query = $em->createNativeQuery($sql, $rsm);
答案 0 :(得分:0)
我使用两个查询解决了这个问题。
这个获取线程的最新消息:
$messages_max = $em->createQueryBuilder()
->select('max(m.id) as id')
->from('BaseBundle:PsMessage', 'm')
->groupBy('m.thread')
->getQuery()
->getResult();
这个显示所有线程:
$qb = $em->createQueryBuilder()
->select('message')
->from('BaseBundle:PsMessage', 'message')
->where('message.receiver = :id')
->orWhere('message.sender = :id')
->andWhere('message.id in (:maxIds)')
->orderBy('message.modifiedDate', 'desc')
->setParameter('id', $userId)
->setParameter('maxIds', $messages_max);