php – Doctrine2 Native Query ManyToMany

我已经阅读了有关本机SQL查询的Doctrine2文档.

它没有讨论由ManyToMany关系加入的实体.

我没有想到如何处理,任何想法或例子. 最佳答案 您只需手动将连接表添加到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();

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

点赞