2012-02-06 106 views
1

据我所知,doctrine dql不允许子查询在一个连接内。Symfony2,Doctrine DQL,子查询,使用条件从另一个表中获取值

我有一个表和一个trasnlation表。这种关系是一对多的关系。一个记录有很多翻译。

为了从translatiosn表我做的SELECT子句中子查询得到正确的翻译行:

 $query = $this->getDoctrine()->getEntityManager() 
      ->createQuery(' 
       SELECT w.id, w.pastid, w.name, w.jsonParameters as params, m.id as milestone_id, m.name as milestone_name, 
       m.slug as milestone_slug, m.startdate as milestone_start, m.enddate as milestone_end, 
       w.expand as expand, w.backgroundcolor as background, w.colorschema as colorschema, w.headline as headline, w.subheadline as subheadline, w.text as text, w.expandheight as expandheight, 
       w.url as url, w.created as created, w.updated as updated, wt.name as wtname, ws.weight as width, ws.height as height 
       , (SELECT t.headline FROM AdminBundle:widgetTranslation t WHERE t.widget = w.id and t.locale = :published) AS headline_trans 
       , (SELECT t2.subheadline FROM AdminBundle:widgetTranslation t2 WHERE t2.widget = w.id and t2.locale = :published) AS subheadline_trans 
       , (SELECT t3.text FROM AdminBundle:widgetTranslation t3 WHERE t3.widget = w.id and t3.locale = :published) AS text_trans 
       FROM AdminBundle:Widget w 
       JOIN w.milestone m 
       JOIN w.widgetType wt 
       JOIN w.widgetShape ws 
       WHERE w.published = 1 
       ORDER BY m.order, w.order 
      ')->setParameter('published', $currentLocale); 

     $result = $query->getArrayResult(); 

这个查询做了工作,但荫担心的表现,有没有更好的查询来做到这一点?

回答

-1

首先,我需要澄清一点点。 有什么真的不对在你的问题。 您正在使用ORM,对吧?但是你在谈论桌子。 ORM不关心你的表是如何组织或链接在一起的。它只关乎对象之间的关系。

但是,如果您担心性能问题,最好的做法是使用任何SQL查询来做到这一点,它就是EXPLAIN它。

由于您使用的是Symfony 2.0,因此您可以使用profiler(可在dev env中访问)查看您的查询的EXPLAIN结果。

确保使用的是索引,并且查找的行数不会太高。

根据您的结果,您可能需要使用其他策略来获取您的翻译或在原生SQL中重新编写查询以提供更大的灵活性。

+0

数据库还有表... – Bart 2012-11-02 14:10:12

+0

@Bart,等等是什么?如果你使用ORM方法,你不应该担心“表”或“数据库”这个词汇与ORM无关,ORM的主要目的是抽象持久层并提供一个对象映射,可能来自关系数据库,xml文档,NoSQL服务器等。您不能使用混合解决方案的50%关系/ 50%对象,您必须在其中一个或另一个之间进行选择。既可以使用Native SQL查询,也可以考虑对象之间的关系,而不是如何在持久层中表示它们。 – 2012-11-05 12:03:08

+0

无论如何。你可以称它们为“表”(db术语)或“集合”或任何你喜欢的东西,但是它们之间的关系将保持不变,在这种情况下是一对多关系。然而,我不同意从ORM严格分离SQL。你改变底层系统多少次?大多数情况下永远不会使用ORM通常在访问属性等时更方便,但是,编写一个(本地)SQL查询有时可以将软件的其他部分的性能提高几个数量级。最终用户不会在乎它是否是ORM/SQL。 – Bart 2012-11-05 17:28:25