symfony querybuilder查询需要编写

时间:2016-02-05 09:35:35

标签: symfony query-builder selectquerybuilder

我在mysql中有以下表格,给定了关系,并且在symfony2中已经定义了相同的表格。我想实现下面的查询,我在下面写下来。有人可以帮助我如何在querybuilder中编写它?

 unitids(id,unitid,databaseid)

 Mappaths(id,ref_unitid2(forigen key for unitids id)  ,ref_unitid1 (forigen key for unitids id),nomal value)

 traveltime(id,ref_map_path(forigen key for mappaths id),  traveltime,noobjs,ondate)

我的mysql查询是这样的:

SELECT t.ID,t.ondate, un.databaseid as source1, 
 un1.databaseid as  desitnation, t.traveltime, t.noobjs 
 FROM test.traveltime t
 left join test.mappaths p on t.ref_map_path = p.ID
 left join test.unitids un on (p.ref_unitids1 = un.id )
 left join test.unitids un1 on (p.ref_unitids2= un1.id)
 where un.databaseid=50 and un1.databaseid =1 limit 1;

给我每一行的源和目的地和对象等,如下所示:  在symfony2中,当我运行此查询时

 $query = $em->createQueryBuilder();
      $results = $query->select('un.databaseid,un1.databaseid')
      ->from('ApiMapBundle:Traveltime', 't')
            ->leftJoin('t.refMapPath', 'p')
            ->leftJoin('p.refUnitids2', 'un')
            ->leftJoin('p.refUnitids1', 'un1')
            ->where('un.databaseid = :bdatabaseid1')
            ->setParameter('bdatabaseid1', 2)
            ->andwhere('un1.databaseid = :bdatabaseid2')
             ->setParameter('bdatabaseid2',1)
            //->setMaxResults(1)
            ->getQuery()
            ->getResult();

它给我输出像

 Array ( [0] => Array ( [databaseid] => 1 ) [1] => Array ( [databaseid] => 1 ))

但它应该给我

  Array ( [0] => Array ( [databaseid] => 1 ) [1] => Array ( [databaseid] => 2 ))

我怎样才能实现上述输出?????

1 个答案:

答案 0 :(得分:1)

假设您正在Repository中编写代码,并且您还在实体中定义了关系

$em = $this->getEntityManager();
$query = $em->getRepository('BUNDLE:traveltime')->createQueryBuilder('t');
$query->select('t.Id,..')
   ->leftJoin('t.ref_map_path','p')
   ->leftJoin('p.ref_unitids1','un')
   ->leftJoin('p.ref_unitids2','un1')
   ->where('un.databaseid = :bdatabaseid')
   ->setParameter('bdatabaseid',1)
   ->orWhere('un1.databaseid = :bdatabaseid1')
   ->setParameter('bdatabaseid1',2);