Symfony 5 (Including 4) using Gedmo Doctrine Extension for SoftDelete

前提是你 提交于 2021-02-05 09:26:29

问题


I have tried to use soft delete (Using gedmo/doctrine-extensions) for some Entities in Symfony 5, and got some troubles:

Listener "SoftDeleteableListener" was not added to the EventManager!

Compile Error: App\Entity\Admin and Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity define the same property ($deletedAt) in the composition of App\Entity\Admin. However, the definition differs and is considered incompatible. Class was composed

This is what I tried, and it runs well

  1. Install gedmo/doctrine-extensions

     composer require gedmo/doctrine-extensions
    
  2. Add column deleted_at to the table what you want to use soft delete (Use migration or add manually)

  3. Add config to config/packages/doctrine.yaml

     filters:
    
         softdeleteable:
    
         class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
    
         enabled: true
    
  4. Add config to config/services.yaml 

     gedmo.listener.softdeleteable:
         class: Gedmo\SoftDeleteable\SoftDeleteableListener
         tags:
             - { name: doctrine.event_subscriber, connection: default }
         calls:
             - [ setAnnotationReader, [ '@annotation_reader' ] ]
    
  5. Add Gedmo and use SoftDeleteableEntity to Your Entity

     <?php
    
     namespace App\Entity;
    
     use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
    
      /**
      * @ORM\Entity(repositoryClass=AdminRepository::class)
      * @ORM\Table(name="admins")
      * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false, 
      hardDelete=false)
     */
     class Admin implements UserInterface
     {
         use SoftDeleteableEntity;
         ….
     }
    
  6. And finally, use delete function as usual, the column deleted_at will be updated

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

Note: Do not need to add deletedAt field, method getDeletedAt and setDeletedAt to Your Entity

来源:https://stackoverflow.com/questions/65895900/symfony-5-including-4-using-gedmo-doctrine-extension-for-softdelete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!