【问题标题】:Doctrine: select query to refresh hydrated entity join?学说:选择查询以刷新水合实体连接?
【发布时间】:2018-11-20 15:26:20
【问题描述】:

一个查询加载一个主实体并将其与被过滤的连接实体结合起来。
具有不同过滤条件的相同查询不会更新连接的实体。

一些数据:

Tiers:
| id | name  |
| 1  | alpha |
| 2  | beta  |

Container:
| id  | tiers_id | category |
| 10  | 1        | A        |
| 20  | 1        | A        |
| 30  | 1        | B        |
| 40  | 1        | B        |

执行 2 次查询以获取一些与其容器相连的层,首先是 A 类,然后是 B 类:

$dql = "select t, c
    from Tiers t
    join t.containers c
    where t.id in (?1) and c.category = (?2)";

$result = $em->createQuery($dql)
    ->setParameter(1, array(1))
    ->setParameter(2, 'A')
    ->getResult();
$tiers = $result[0];
$containers = $tiers->getContainers(); // tiers 1 with containers 10 and 20, that's fine !

$result = $em->createQuery($dql)
    ->setParameter(1, array(1))
    ->setParameter(2, 'B')
    ->getResult();
$tiers = $result[0];
$containers = $tiers->getContainers(); // BAD HERE: still get containers 10 and 20, looking for containers 30 and 40.

在第二次查询之后,第 1 层保留在第一次查询期间加载的容器。这不是预期的。
那么有没有办法在第二次查询后获取容器 30 和 40?
在第一次查询之后,也许是一种“重置/分离”层实体的容器?
或者别的什么...


查询中的多项选择用于对加入了所需容器的层进行水合。
'getContainers' 方法给出了来自每一层的预期容器。
而且无论搜索的层数是多少,BDD 的成本仅为 1 个 SQL 查询。


我想层不能分离/重新加载,因为它们在查询之前、之间和之后更新,刷新时会抛出这种异常:

Uncaught Exception: Multiple non-persisted new entities were found through the given association graph
* A new entity was found through the relationship 'XXX' that was not configured to cascade persist operations for entity: XXX\Entity\Tiers@00000000257b87500000000018499b62.

【问题讨论】:

标签: symfony doctrine-orm


【解决方案1】:

在第二次查询之前重置层的容器:

foreach($result as $tiers)
    $tiers->nullContainers();

向 Entity\Tiers 添加方法:

public function nullContainers()
{
     this->containers = null;
}

然后第二个查询“刷新”层的容器。

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2016-01-14
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多