Skip to content

Update builder

What is UpdateBuilder ?

Update builder is a suit of classes to allow you to update records of database in mass.

It use a where clause responding to same rules as QueryBuilder but you can specify fields to update.

Update all records

To update all records of a table in database, use UpdateBuilder without where clause :

$userManager = $this->entityManagerFactory
    ->get(UserManager::class);

$query = $userManager->createUpdateBuilder('userAlias')
    ->addFieldToUpdate('username', 'updated')
;

$userManager->executeUpdate($query);

All usernames will be updated to "updated".

Where clause

You can use where to select records to update.

The where clause work same as QueryBuilder.

$userManager = $this->entityManagerFactory
    ->get(UserManager::class);

$query = $userManager->createUpdateBuilder('userAlias')
    ->addFieldToUpdate('username', 'updated')
    ->addFieldToUpdate('password', 'secret')
;

$query->where()
    ->firstCondition(
        $query->getFieldForCondition('status'), 
        ConditionOperatorType::equal,
         ':status'
     )
;

$query->setParameter('status', 'pending');

$userManager->executeUpdate($query);

Enabling triggers

By default, UpdateBuilder query skip triggers beforePersist, afterPersist, beforeUpdate and afterUpdate for performance purpose, but it is possible to activate them by passing false in second parameter.

class UserEntity extends AbstractEntity
    implements BeforeUpdateInterface, AfterUpdateInterface
{

    public static int $numUsers = 0;

    #[PrimaryKey]
    public ?int $id;

    #[Field(FieldValueType::string)]
    public ?string $username = null;

    #[Field(FieldValueType::dateTime)]
    public ?\DateTime $updatedAt = null;

    #[ToMany(ProjectManager::class, ['id' => 'userId'])]
    public ?ProjectCollection $projects = null;

    publc function beforeUpdate(): void
    {

        $this->updatedAt = new \DateTime();

    }

    public function afterUpdate(): void
    {

        EventDispatcher::dispatch(
            new UserUpdatedEvent($this);
        );

    }

}

$userManager = $this->entityManagerFactory
    ->get(UserManager::class);

$query = $userManager->createUpdateBuilder('userAlias')
    ->addFieldToUpdate('username', 'nick')
    ->addFieldToUpdate('password', 'secret')
;

$userManager->executeUpdate($query, false);

Here, the field updatedAt will be set and UserUpdatedEvent will be dispatched.

Next chapter : Delete builder