gpt4 book ai didi

php - 如何使用来自非托管实体的数据正确更新托管实体?

转载 作者:可可西里 更新时间:2023-11-01 12:53:17 24 4
gpt4 key购买 nike

上下文

我的目标是使用来自同一类但不受 Doctrine 管理的对象的数据对托管实体执行更新。

如果可以在替换属性时执行“简单更新”,这会很酷,但实际上,如果我清理 ArrayCollection,旧数据似乎不会被删除(即使我从 ArrayCollection 的元素或如果 orphanRemoval 设置为 true 时清除所有对 fiddle 的引用。

但是让我们输入一个具体的例子。我有 this entity有很多 OneToOne/OneToMany 关系来表示 fiddle .我可以使用 Symfony2 命令导入 fiddle 样本(之前从另一个环境导出为 json)。

如果示例已经存在,我该如何正确更新它?

坏主意:做 DELETE + INSERT

我使用以下代码(简化)构建我的实体:

$fiddle = new Fiddle();
$fiddle->setHash($this->get($json, 'hash'));
$fiddle->setRevision($this->get($json, 'revision'));

$context = $fiddle->getContext();
$context->setFormat($this->get($json, 'context', 'format'));
$context->setContent($this->get($json, 'context', 'content'));

$fiddle->clearTemplates();
$jsonTemplates = $this->get($json, 'templates') ? : array ();
foreach ($jsonTemplates as $jsonTemplate)
{
$template = new FiddleTemplate();
$template->setFilename($this->get($jsonTemplate, 'filename'));
$template->setContent($this->get($jsonTemplate, 'content'));
$template->setIsMain($this->get($jsonTemplate, 'is-main'));
$fiddle->addTemplate($template);
}

// ...

如果实体已经存在,我现在可以在删除实体后保留它:

    $check = $this
->getContainer()
->get('doctrine')
->getRepository('FuzAppBundle:Fiddle')
->getFiddle($fiddle->getHash(), $fiddle->getRevision());

if (!is_null($check->getId()))
{
$em->remove($check);
$em->flush();
}

$em->persist($fiddle);
$em->flush();

但是如果样本已经存在,这将创建一个 DELETE + INSERT 而不是 UPDATE。这很奇怪,因为用户可以为 fiddle 添加书签,并且这种关系是由 id 建立的。

丑陋的想法:对主要实体和 OneToOne 关系进行更新,并对 OneToMany 关系进行 DELETE + INSERT

我先得到我的 fiddle ,如果它已经存在,我会清理它并用新数据填充它......代码运行良好但真的很丑,你可以检查它here .

作为示例,检查 tags 属性:由于标签可能已被删除/更改,我应该正确设置新标签,将旧标签替换为新标签。

// remove the old tags
foreach ($fiddle->getTags() as $tag)
{
if (\Doctrine\ORM\UnitOfWork::STATE_MANAGED === $em->getUnitOfWork()->getEntityState($tag))
{
$em->remove($tag);
$em->flush();
}
}

// set the new tags
$tags = new ArrayCollection();
$jsonTags = $this->getFromArray($json, 'tags');
foreach ($jsonTags as $jsonTag)
{
$tag = new FiddleTag();
$tag->setTag($jsonTag);
$tags->add($tag);
}
$fiddle->setTags($tags);

由于标签是使用 fiddle 的 id 引用的,所以我可以使用 ->remove,即使那很丑陋。这在这里没问题,但如果 ID 是自动生成的,则必须有更好的解决方案。

我还尝试简单地将旧 fiddle 的 id 设置为新 fiddle 的 id 并合并,但这导致了以下异常:

[Symfony\Component\Debug\Exception\ContextErrorException]  
Notice: Undefined index: 00000000125168f2000000014b64e87f

赏金?

不仅仅是一个简单的“导入功能”,我想使用这种更新样式将表单绑定(bind)到非托管实体并仅在需要时更新现有实体。所以我的目标是让一些通用的东西适用于所有类型的实体。

但我当然不期望整个代码。处理托管 ArrayCollection 更新的良好做法,以及一些关于我在编写此功能之前应该考虑的事项的提示/警告应该足够了。

最佳答案

控制什么 Doctrine 持续存在

Update existing entities only if required.

这可以通过 Doctrine 相当简单地实现:

您正在寻找的是变更跟踪政策 Deferred Explicit .

Doctrine 默认使用变更跟踪策略 Deferred Implicit .这意味着当你调用 $em->flush() 时,Doctrine 将遍历 所有 它的托管实体来计算变更集。然后保留所有更改。

使用更改跟踪策略时 Deferred Explicit并调用 $em->flush(),Doctrine 将遍历您明确调用的实体 $em->persist()在。换句话说:你可能有成千上万的托管实体,其中 2 个被称为 $em->persist(),而 Doctrine 将只计算这 2 个的变更集(并在需要时持久化变更) ).

可以在实体类级别设置更改跟踪策略。所以如果你想让某个实体类使用Deferred Explicit ,只需向类文档 block 添加注释:

/**
* @Entity
* @ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class Fiddle
{

然后只需在真正需要时调用 $em->persist($fiddle) 即可。

为整个聚合(根实体及其所有子实体)设置相同的更改跟踪策略可能是明智的。

PS:还有第三个更改跟踪策略,名为 Notify ,这需要做更多的设置工作,但可以让您更精细地控制调用 $em->flush() 时保留的内容。但我认为您不需要走这么远。

更新 fiddle

看到您用来更新 Fiddle 实体的代码,我认为您可以在那里改进一些东西。

首先将管理关联的责任移回实体:

/**
* @Entity
* @ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class Fiddle
{
// ...

/**
* @return FiddleTag[]
*/
public function getTags()
{
return $this->tags->toArray();
}

/**
* @param FiddleTag $tag
*/
public function addTag(FiddleTag $tag)
{
if (!$this->tags->contains($tag)) {
$this->tags->add($tag);
$tag->setFiddle($this);
}
}

/**
* @param FiddleTag $tag
*/
public function removeTag(FiddleTag $tag)
{
if ($this->tags->contains($tag)) {
$this->tags->removeElement($tag);
$tag->setFiddle(null);
}
}

/**
* @param FiddleTag[] $newTags
*/
public function replaceTags(array $newTags)
{
$currentTags = $this->getTags();

// remove tags that are not in the new list of tags
foreach ($currentTags as $currentTag) {
if (!in_array($currentTag, $newTags, true)) {
$this->removeTag($currentTag);
}
}

// add tags that are not in the current list of tags
foreach ($newTags as $newTag) {
if (!in_array($newTag, $currentTags, true)) {
$this->addTag($newTag);
}
}
}

// ...
}

现在您的 ImportCommand 中的代码看起来像这样:

$jsonTags = $this->getFromArray($json, 'tags');
$newTags = [];

foreach ($jsonTags as $jsonTag) {
$tag = $tagRepo->findOneByTag($jsonTag);

if ($tag === null) {
$tag = new FiddleTag();
$tag->setTag($jsonTag);
}

$newTags[] = $tag;
}

$fiddle->replaceTags($newTags);

然后当一切正常,可以持久化时,做:

$em->persist($fiddle);

foreach ($fiddle->getTags() as $tag) {
$em->persist($tag);
}

$em->flush();

在关联上配置了 cascade=persist 后,您应该能够省去手动保留标签的循环。

专业提示

你可以看看 JMS Serializer图书馆和 Bundle将其集成到 Symfony 中。

关于php - 如何使用来自非托管实体的数据正确更新托管实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com