php - 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?
解决方案
我猜您缺少的是启用弹性收据添加的文件config/packages/stof_doctrine_extensions.yaml中的扩展名。
看起来,默认情况下,它读取
stof_doctrine_extensions:
default_locale: en_US
什么时候,如果你想使用软删除,你需要激活它:
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
softdeleteable: true
推荐阅读
- javascript - React JS-else 块未在 Map 函数内执行
- c - 尝试多个巨大的 int 但得到 1 的乘积
- c++ - 如何在 Visual Studio 2017 中构建和调试 MSYS2 / MinGW64 / CMake 项目?
- java - 如何将控制权返回到 Excel 工作表中的第一列?
- javascript - 在 Node Media Server (Nodejs) 中禁用/拒绝除 ws:// 之外的所有协议
- java - Java Springboot中的服务器端渲染React
- json - 数组中的 CouchDB 字段查询
- excel - 运行时错误“424”:需要检查动态命名范围是否为空的对象
- ruby-on-rails - 手动数组上的 Rails 属性
- sql - 同时插入新表和连接表