Symfony 4结合Doctrine ORM实现软删除

7
我希望将特定实体进行软删除(而不是所有实体)。我已经安装了StofDoctrineExtensionsBundle扩展包,这应该给我提供Softdeleteable功能。
所以我更新了我的实体:

User.php

<?php 
namespace App\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, hardDelete=false)
 */
class User implements UserInterface
{

    use SoftDeleteableEntity;

我创建了迁移并运行了迁移。我的表User现在有一个额外的列deleted_at
根据文档,现在可以运行此代码以软删除记录:
public function delete(User $user, EntityManagerInterface $em)
{
     $em->remove($user);
     $em->flush();

然而,这会导致错误,因为用户实体具有关系,用户本身无法被删除。当然,这就像我编程时所做的一样。但我并不真正想删除记录,我想软删除记录。

An exception occurred while executing 'DELETE FROM user WHERE id = ?' with params [79]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`thedatabase`.`shoppingcart`, CONSTRAINT `FK_932C7444A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))

阅读文档时,提到了设置软删除的内容。但说实话,我不知道如何解决这个问题。

我该如何在Symfony 4中使用软删除?


你是如何安装的?通过Symfony Flex还是没有使用它? - β.εηοιτ.βε
我使用了Symfony Flex。 - Timo002
3
你激活了这个扩展吗?请参考 https://symfony.com/doc/master/bundles/StofDoctrineExtensionsBundle/configuration.html#activate-the-extensions-you-want - acucchieri
@EquaPro,忘记激活它了...谢谢! - Timo002
2个回答

12

我猜你遗漏的是启用扩展,它在文件config/packages/stof_doctrine_extensions.yaml中,这个文件是由flex receipt添加的。

看起来,默认情况下,它读取这里的内容。

stof_doctrine_extensions:
    default_locale: en_US

如果您想使用软删除功能,则需要激活它:

stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            softdeleteable: true

是的,忘记在 stof_doctrine_extensions 中添加 softdeletable: true。谢谢! - Timo002
不要忘记过滤器功能:https://symfony.com/doc/1.x/bundles/StofDoctrineExtensionsBundle/softdeleteable-filter.html - Wesley Abbenhuis

1
我还需要在doctrine.yaml中包含这个内容:

doctrine: dbal:

在这里输入您的dbal配置

orm:
    auto_generate_proxy_classes: %kernel.debug%
    auto_mapping: true

只有这些行是额外添加的

    filters:
        softdeleteable:
            class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
            enabled: true #this one doesn't was in the doc, I found it in an issue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接