Cou*_*les 5 php entity doctrine-orm
我的数据库中的 FK 已损坏,如果我加载一个实体并请求相关实体 Doctrine 将抛出\Doctrine\ORM\EntityNotFoundException。
对于有问题的实体,我更希望在 FK 损坏的地方返回 NULL 而不是抛出异常。这是因为异常发生在 Twig 模板内,我希望 Twig 在这种情况下不必处理异常。
以下是配置示例。
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Foo\Click" table="clicks">
<id name="id" type="bigint" column="click_id">
<generator strategy="IDENTITY"/>
</id>
<!-- .. -->
<many-to-one field="visitor" target-entity="Foo\Visitor" fetch="LAZY">
<join-columns>
<join-column name="visitor_id" referenced-column-name="visitor_id"/>
</join-columns>
</many-to-one>
</entity>
<entity name="Foo\Visitor" table="visitors" read-only="true">
<id name="visitorId" type="integer" column="visitor_id">
<generator strategy="IDENTITY"/>
</id>
<!-- ... -->
<one-to-one field="firstClick" target-entity="Foo\Click" fetch="LAZY">
<join-columns>
<join-column name="click_id" referenced-column-name="click_id"/>
</join-columns>
</one-to-one>
</entity>
</doctrine-mapping>
Run Code Online (Sandbox Code Playgroud)
以下是预期结果的示例,其中点击作为访客 ID,但不存在具有该 ID 的访客记录。在这种情况下,我宁愿不必将逻辑包装在 Try/Catch 中,而是使用Click::getVisitor()return null;
<?php
$clickOne = $entityManager()->find(Foo\Click::class, 1);
$v = $clickOne->getVisitor();
if ($v !== null) {
echo $v->getId(); // may throw Doctrine\ORM\EntityNotFoundException
}
Run Code Online (Sandbox Code Playgroud)
Doctrine 对此有策略吗?
更新:添加了示例配置和代码,现在我明白了为什么通过简单的 Doctrine 配置无法实现这一点。
这是我根据iainn的评论采取的策略。
<?php
class Parent
{
protected $child;
public function getChild()
{
if ($this->child instance of \Doctrine\ORM\Proxy\Proxy) {
try {
$this->child->__load();
} catch (\Doctrine\ORM\EntityNotFoundException $e) {
$this->child = null
}
}
return $this->child;
}
}
Run Code Online (Sandbox Code Playgroud)
我确信不建议您的实体直接与代理交互。但我更喜欢这样做,而不是在实体上调用已知方法(这也会产生加载它的效果),因为对于下一个可能阅读它的开发人员来说,此代码的意图更清楚。
我不确定与这样的代理交互是否有任何副作用。