我需要从数据库中随机选择3个元素,所以我尝试使用这个查询:
$em = $this->getEntityManager('MyBundle:Gift');
$rsm = new ResultSetMapping();
$rsm->addEntityResult('MyBundle:Gift', 'g1');
$rsm->addFieldResult('g1', 'id', 'id');
$rsm->addFieldResult('g1', 'image', 'image');
$rsm->addFieldResult('g1', 'special', 'special');
$rsm->addFieldResult('g1', 'activationDate', 'activationDate');
// Compute carthesian product to generate all possible combinations
$result = $em->createNativeQuery(
"SELECT * FROM gift g1, gift g2, gift g3 ORDER BY RAND() LIMIT 3", $rsm
)->getResult();
在MySQL上运行查询总是产生三个结果行,但不知道Doctrine有时会得到2个结果。
也许我没有使用ResultSetMapper,我不太了解它的API。