我在构建 Doctrine 查询(在 Symfony 项目中)时遇到了很多麻烦,我刚刚完成它并且它可以工作,但我想获得你的建议,我不确定我的解决方案是最好的.
为了简单起见,我有 3 个 SQL 表:Workshop、News和Comment。他们中的最后两个与 Workshop 处于多对一关系。
我的目标是在一个页面上显示一个 Workshop 实体以及相关的 News 和 Comment 实体。为了使事情复杂一点,我只需要显示最后 5 个 News 和 Comment 实体。当然,这应该只在一个查询中完成(作为故障排除,我一直使用延迟加载)。
我设法进行了这个本机查询:
SELECT *
FROM Workshop w
LEFT JOIN (
SELECT * FROM News ORDER BY id DESC LIMIT 0, 5
) n ON w.id = n.workshop_id
LEFT JOIN (
SELECT * FROM Comment ORDER BY id DESC LIMIT 0, 5
) c ON w.id = c.workshop_id
WHERE w.id = 1 -- Random ID as an exemple
在此之后,我想将其转换为 DQL,但这种语言不支持 FROM 和 JOIN 部分内的嵌套查询。
我最后的选择是使用本机查询......过了一会儿,我已经能够在我的 Workshop 存储库中获得这个结果:
<?php
public function getWorkshopWithAllContent()
{
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('FON\WorkshopBundle\Entity\Workshop', 'w', array(
'id' => 'wId'
));
$rsm->addJoinedEntityFromClassMetadata('FON\WorkshopBundle\Entity\News', 'n', 'w', 'news', array(
'id' => 'nId',
'title' => 'nTitle',
'content' => 'nContent',
'pubDatetime' => 'nPubDatetime',
'validated' => 'nValidated',
'workshop_id' => 'nWorkshop_id'
));
$rsm->addJoinedEntityFromClassMetadata('FON\WorkshopBundle\Entity\Comment', 'c', 'w', 'comments', array(
'id' => 'cId',
'title' => 'cTitle',
'content' => 'cContent',
'pubDatetime' => 'cPubDatetime',
'validated' => 'cValidated',
'workshop_id' => 'cWorkshop_id'
));
$query = $this->_em->createNativeQuery(
'SELECT '.
'w.id wId, w.town, w.description, w.zipcode, w.address, '.
'n.id nId, n.title nTitle, n.content nContent, n.pubDatetime nPubDatetime, n.validated nValidated, n.workshop_id nWorkshop_id, '.
'c.id cId, c.title cTitle, c.content cContent, c.pubDatetime cPubDatetime, c.validated cValidated, c.workshop_id cWorkshop_id '.
'FROM Workshop w '.
'LEFT JOIN ( '.
' SELECT * FROM News ORDER BY id DESC LIMIT 0, 5 '.
') n ON w.id = n.workshop_id '.
'LEFT JOIN ( '.
' SELECT * FROM Comment ORDER BY id DESC LIMIT 0, 5 '.
') c ON w.id = c.workshop_id '.
'WHERE w.id = 1 ',
$rsm
);
return $query->getOneOrNullResult();
}
那么,为什么要重新定义几乎所有的列呢?因为如果我不这样做,就像这样:
<?php
public function getWorkshopWithAllContent()
{
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('FON\WorkshopBundle\Entity\Workshop', 'w');
$rsm->addJoinedEntityFromClassMetadata('FON\WorkshopBundle\Entity\News', 'n', 'w', 'news');
$rsm->addJoinedEntityFromClassMetadata('FON\WorkshopBundle\Entity\Comment', 'c', 'w', 'comments');
$query = $this->_em->createNativeQuery(
'SELECT * '.
'FROM Workshop w '.
'LEFT JOIN ( '.
' SELECT * FROM News ORDER BY id DESC LIMIT 0, 5 '.
') n ON w.id = n.workshop_id '.
'LEFT JOIN ( '.
' SELECT * FROM Comment ORDER BY id DESC LIMIT 0, 5 '.
') c ON w.id = c.workshop_id '.
'WHERE w.id = 1 ',
$rsm
);
return $query->getOneOrNullResult();
}
我收到此错误:
The column 'id' conflicts with another column in the mapper.
就是这样!我现在的问题是:有更好的解决方案吗?我的真的很长,我很惊讶 Doctrine 没有想到一个解决方案。
解决此问题的永久方法是重命名表的所有列,但我想知道在此之前是否有更简单的解决方案。
谢谢你。