2014-12-09 133 views
0

我有两个DB与OneToMany关系的表。在'EntityRepository'中使用'createQueryBuilder()'方法,我尝试选择一些具有条件的对象。有我的方法:Symfony 2 OneToMany的关系 - 关联错误的结果

$query = $this->getEntityManager()->createQueryBuilder(); 
    $query->select("parent") 
     ->from('TestAppBundle:Parent', 'parent') 
     ->leftJoin("parent.children", 'child', 'WITH', 'child.IdP = parent.id') 
     ->where('child.date < :date') 
     ->andWhere('child.status = :null') 
     ->setParameter('date', new DateTime()) 
     ->setParameter('null', 0); 

它的工作几乎不错。我在ArrayCollections中获取具有子对象的父对象。方法选择具有条件的父对象,但问题是我也得到不保留条件的子对象。 我想只得到保持条件的子对象和也保持条件的子对象。此时必须在查询后过滤结果并手动删除儿童对象。 我希望你能理解这个问题:)

+0

被选中的孩子不符合的条件是什么? – Jeroen 2014-12-09 13:29:42

+0

孩子有字段名称“状态”。该字段可以是真或假。我只想选择这个孩子的状态为false的父母。它工作正常,从8000行我得到100个父对象,但是当我想看到孩子,我得到状态为真的孩子和状态为假的孩子。查询后必须删除状态为真的子对象。 – semafor 2014-12-09 13:45:29

回答

0

基本上,如果你不选择在查询时的实体你会延迟加载所有儿童的父母当你调用getChildren()。选择这两个孩子和家长这样避免延迟加载:

$query->select("parent, child") 

欲了解更多信息,请参阅my answer to a similar question

+0

感谢它的工作!我之前尝试过这种方式,但我想我得到了具有混合值的集合父母和孩子(一种水平数组中的两种类型的对象)。这不是真的。 – semafor 2014-12-11 08:02:09

0

你能尝试这样的事:

$query = $this->getEntityManager()->createQueryBuilder(); 
$query->select("parent") 
    ->from('TestAppBundle:Parent', 'parent') 
    ->leftJoin("parent.children", 'child', 'WITH', 'child.status = 0'); 
+0

不幸的是它并没有改变任何东西。我仍然需要许多子对象。 – semafor 2014-12-09 14:45:11

+0

为了不好,你能否提供一些数据库信息或教条映射文件(如果你使用教条)。 – Jeroen 2014-12-09 14:52:48

0

据我了解你的需求,你不应该使用leftJoin - 与这个领域,你会得到没有孩子的父母。改为使用innerJoin

假设child.IdP引用模型定义中的parent.id,您不必以这种方式使用WITH子句。所以queryBuilder将是:

$query = $this->getEntityManager()->createQueryBuilder(); 
$query->select("parent") 
    ->from('TestAppBundle:Parent', 'parent') 
    ->innerJoin("parent.children", 'child') 
    ->where('child.date < :date and child.status = :null') 
    ->setParameter('date', new DateTime()) 
    ->setParameter('null', 0); 

问候。