Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 softdelete with Doctrine ORM

Tags:

php

symfony

I want a specific entity to be softdeleted (not all Entities). I've installed the StofDoctrineExtensionsBundle bundle which should give me the Softdeleteable feature.

So I updated my Entity:

User.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;

I created the migration and run the migration. My table User now as an extra column deleted_at.

Following the documentation I should now be possible to run this code to softdelete a record:

public function delete(User $user, EntityManagerInterface $em)
{
     $em->remove($user);
     $em->flush();

This however throws me an error because the User entity has relations and the User itself cannot be deleted. Sure, this is like I programmed is. But I do not really want to delete the record, I want to softdelete the record.

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`))

When reading the documentation, it mentions something about settingup softdelete. But to be honest, I have no clue on how to fix that.

How can I make use of softdelete in Symfony 4?

like image 894
Timo002 Avatar asked Mar 18 '19 22:03

Timo002


1 Answers

I would guess that what you are missing is to enable the extension in the file config/packages/stof_doctrine_extensions.yaml that was added by the flex receipt.

It looks like, per default, it reads

stof_doctrine_extensions:
    default_locale: en_US

When, if you want to use soft deletable, you would need to activate it:

stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            softdeleteable: true
like image 60
β.εηοιτ.βε Avatar answered Sep 29 '22 05:09

β.εηοιτ.βε