Symfony2:在树枝中显示获取连接结果

时间:2015-05-18 09:13:58

标签: php symfony doctrine-orm

我只想列出一个表(建筑物)视图中的所有实体,这需要一个连接来显示一些细节(建筑物管理)。我想使用Doctrine fetch join选项来避免额外的查询,因为每个建筑物都必须从其建筑物管理中显示其数据。

以下是一个基本的控制器示例。我的问题是必须在select中包含bm才能使用fetch而不是常规join。因此,$entities变量包含bbm个实体,而Twig中的循环只等待b个实体。我该如何解决?

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    // This way is working, but extra queries are generated when I need to access the BuildingManagement data from Building entity
    //$entities = $em->getRepository('TrilogisPropertyBundle:Building')->findAll();

    $entities = $em->createQuery(
            'SELECT b, bm
             FROM MyBundle:Building b
             JOIN MyBundle:BuildingManagement bm WITH bm.building = b.id
             ORDER BY b.id')                                   
            ->getResult();

    return $this->render('MyBundle:Test:index.html.twig', array(
        'entities' => $entities,
    ));
}

在TWIG

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Building Management</th>
        </tr>
    </thead>
    <tbody>
    {% for entity in entities %}
        <tr>
            <td>{{ entity.id }}</td>     
            <td>{{ entity.buildingManagement.id}}</td> <-- will crash because the entity must be a building and not a buildingManagement                                            
        </tr>
    {% endfor %}
    </tbody>
</table>

1 个答案:

答案 0 :(得分:2)

如果您所说的关于在评论中将这两者之间的关系说出来的话,那么您可能会以错误的方式Notification notif = new Notification( R.drawable.ic_launcher, message, System.currentTimeMillis()); notif.flags = Notification.FLAG_AUTO_CANCEL; notif.defaults |= Notification.DEFAULT_SOUND; notif.defaults |= Notification.DEFAULT_VIBRATE; Intent notificationIntent = new Intent(context, WelcomeActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notif.setLatestEventInfo(context, title, message, contentIntent); 做错:

查询应该是:

JOIN

有些注意事项:

  • 您需要$entities = $em->createQuery( 'SELECT b, bm FROM MyBundle:Building b JOIN b.buildingManagement bm ORDER BY b.id') ->getResult(); 实体中的buildingManagement成员才能使其生效。
  • 从它的外观来看,
  • Building应注明buildingManagement。可能是@ManyToOne,但这取决于应用程序的逻辑。
  • 可选地,@ManyToMany应标记为反转。如果您使用实体(两者)更新您的问题,我们可以帮助您确定。