【问题标题】:Symfony 2 OneToMany relations - wrong results in associationSymfony 2 OneToMany 关系 - 关联错误
【发布时间】:2014-12-09 12:19:58
【问题描述】:

我在 DB 中有两个具有 OneToMany 关系的表。在“EntityRepository”中使用“createQueryBuilder()”方法,我尝试选择一些有条件的对象。有我的方法:

    $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 中得到带有子对象的父对象。方法选择具有条件的父对象,但问题是我也得到不保持条件的子对象。 我只想获得保持条件的父对象和也保持条件的子对象。此时必须在查询后过滤结果并手动删除子对象。 我希望你能理解这个问题:)

【问题讨论】:

  • 被选中的孩子不满足什么条件?
  • 孩子有即字段名称“状态”。该字段可以为真或假。我只想选择这个孩子的状态为假的父母。它工作正常,从即 8000 行我得到 100 个父对象,但是当我想看到孩子时,我得到状态为真的孩子和状态为假的孩子。我必须删除查询后状态为 true 的子对象。

标签: php symfony doctrine-orm relational-database


【解决方案1】:

基本上,如果您在查询时不选择实体,您将在调用 getChildren() 时为父级延迟加载所有子级。像这样选择孩子和父母以避免延迟加载:

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

更多信息请查看my answer to a similar question

【讨论】:

  • 感谢它的工作!我以前尝试过这种方式,但我认为我得到了混合值父母和孩子的集合(一个级别数组中的两种类型的对象)。这不是真的。
【解决方案2】:

你可以试试这样的:

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

【讨论】:

  • 不幸的是它并没有改变任何东西。我还有很多子对象。
  • 很糟糕,您能否提供一些数据库信息或学说映射文件(如果您使用学说)。
【解决方案3】:

据我了解您的需求,您不应使用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);

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多