Symfony 5(包括4)使用Gedmo Doctrine扩展SoftDelete



我尝试使用软删除(使用gedmo/doctrine-extensions)在Symfony 5中的一些实体,并得到了一些麻烦:

侦听器"SoftDeleteableListener"未添加到EventManager!

编译错误:AppEntityAdmin和GedmoSoftDeleteableTraitsSoftDeleteableEntity在AppEntityAdmin的组成中定义了相同的属性($deletedAt)。然而,定义不同,被认为是不相容的。类组成

这是我试过的,它运行良好

  1. 安装gedmo/doctrine-extensions

    composer require gedmo/doctrine-extensions
    
  2. 添加列deleted_at到表中你想使用软删除(使用迁移或手动添加)

  3. 添加config到config/packages/doctrine.yaml

    filters:
    softdeleteable:
    class: GedmoSoftDeleteableFilterSoftDeleteableFilter
    enabled: true
    
  4. 添加config到config/services。yaml

    gedmo.listener.softdeleteable:
    class: GedmoSoftDeleteableSoftDeleteableListener
    tags:
    - { name: doctrine.event_subscriber, connection: default }
    calls:
    - [ setAnnotationReader, [ '@annotation_reader' ] ]
    
  5. 添加Gedmo并使用SoftDeleteableEntity到您的实体

    <?php
    namespace AppEntity;
    use GedmoSoftDeleteableTraitsSoftDeleteableEntity;
    /**
    * @ORMEntity(repositoryClass=AdminRepository::class)
    * @ORMTable(name="admins")
    * @GedmoSoftDeleteable(fieldName="deletedAt", timeAware=false, 
    hardDelete=false)
    */
    class Admin implements UserInterface
    {
    use SoftDeleteableEntity;
    ….
    }
    
  6. 最后,像往常一样使用delete函数,deleted_at列将被更新

    /**
    * @param Admin $admin
    */
    public function delete(Admin $admin)
    {
    $this->_em->remove($admin);
    $this->_em->flush();
    }
    

注意:不需要添加deletedAt字段,方法getDeletedAtsetDeletedAt到您的实体

如果您使用PHP格式(config/services.php)而不是YAML,请将步骤4更改为以下内容。

$services->set("gedmo.listener.softdeleteable")
->class(GedmoSoftDeleteableSoftDeleteableListener::class)
->tag(name: 'doctrine.event_subscriber', attributes: ["method" => "setAnnotationReader", "connection" => "default"])
->args([service('doctrine.orm.metadata.annotation_reader')])
;

最新更新