Doctrine2 Native Query ManyToMany

时间:2012-11-30 21:36:34

标签: php mysql symfony doctrine-orm

我已经阅读了有关本机sql查询的Doctrine2文档。 它没有讨论由ManyToMany关系加入的实体。 我没有想到如何处理,任何想法或例子。

1 个答案:

答案 0 :(得分:2)

您只需手动将连接表添加到sql中。在Doctrine手册的第14章中扩展了这个例子:

$rsm = new ResultSetMapping;
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addJoinedEntityResult('Address' , 'a', 'u', 'address');
$rsm->addFieldResult('a', 'address_id', 'id');
$rsm->addFieldResult('a', 'street', 'street');
$rsm->addFieldResult('a', 'city', 'city');

$sql = 'SELECT u.id, u.name, a.id AS address_id, a.street, a.city FROM users u ' .
       'INNER JOIN address__user j ON u.id = j.user '.
       'INNER JOIN address a ON a.id = j.address '.
       'WHERE u.name = ?';
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

此示例假定您的连接表具有字段地址和用户的键。