我想要一个特定的实体被软删除(不是所有的实体)。我已经安装了StofDoctrineExtensionsBundle包,它应该会给我Softdeleteable功能。
所以我更新了我的实体:
用户名
<?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;
Run Code Online (Sandbox Code Playgroud)
我创建了迁移并运行了迁移。我的表现在User作为一个额外的列deleted_at。
按照文档,我现在应该可以运行此代码来软删除记录:
public function delete(User $user, EntityManagerInterface $em)
{
$em->remove($user);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
然而,这会引发我的错误,因为 User 实体具有关系并且无法删除 User 本身。当然,这就像我编程的那样。但我并不是真的想删除记录,我想软删除记录。
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`))
Run Code Online (Sandbox Code Playgroud)
在阅读文档时,它提到了一些关于设置软删除的内容。但老实说,我不知道如何解决这个问题。
如何在 Symfony 4 中使用 softdelete?
我猜你缺少的是在由 flex 收据添加的文件config/packages/stof_doctrine_extensions.yaml中启用扩展。
看起来,默认情况下,它读取
stof_doctrine_extensions:
default_locale: en_US
Run Code Online (Sandbox Code Playgroud)
如果您想使用软删除,则需要激活它:
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
softdeleteable: true
Run Code Online (Sandbox Code Playgroud)