skip to Main Content

There’s isDefault property in an entity. If it’s set to true, the isDefault property of all other entities must be set to false.

Is there a clean solution without the QueryBuilder or plain SQL? And if so, what is the solution.

TLDR: How can I update one ore more values of any entity whose ID IS NOT a specific one?

Update

I have a table of entities. Only one entity can have a (bool) isDefault status. If I create a new entity, which can be set to isDefault = true all other entities must be set to isDefault = false.

2

Answers


  1. Chosen as BEST ANSWER

    The solution is not to update all other entities whose state can already be isDefault = false but to update only those which have the state isDefault = true.

    $entities = $entityManager->getRepository( Entity::class )
        ->findBy(
            [
                'isDefault' => true
            ]
        );
    foreach( $entities as $entity )
    {
        $entity->setIsDefault( false );
    }
    
    $newEntity = new Entity();
    $newEntity->setIsDefault( true );
    $entityManager->persist( $newEntity );
    
    $entityManager->flush();
    

    It would be possible to use findOneBy() but this is the more safe approach to prevent multiple entities with the same isDefault = true status.


  2. You can mark the relation to cascade-all and then use setters with persist to persist updates.
    Read Doctrine: Transitive persistence / Cascade Operation for more info.

    class Entity {
    
      #[Column(type: Types::INTEGER)]
      protected bool $isDefault;
    
      #[OneToMany(..., cascade: ['persist', 'remove'])]
      protected Collection $children;
    
    
      public function setIsDefault(bool $isDefault) {
        $this->isDefault = true;
        foreach ($this->children as $child) {
          $child->setIsDefault($isDefault);
        }
      }
    }
    
    // In your code:
    $entity->setIsDefault(true);
    $entityManger->persist($entity);
    $entity->flush();
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search