首页 > 解决方案 > Symfony 4 软删除与 Doctrine ORM

问题描述

我希望软删除特定实体(不是所有实体)。我已经安装了StofDoctrineExtensionsBundle包,它应该给我Softdeleteable功能。

所以我更新了我的实体:

用户.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`))

在阅读文档时,它提到了一些关于设置 softdelete 的内容。但老实说,我不知道如何解决这个问题。

如何在 Symfony 4 中使用 softdelete?

标签: phpsymfony

解决方案


我猜您缺少的是启用弹性收据添加的文件config/packages/stof_doctrine_extensions.yaml中的扩展名。

看起来,默认情况下,它读取

stof_doctrine_extensions:
    default_locale: en_US

什么时候,如果你想使用软删除,你需要激活它:

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

推荐阅读