Delete BuilDer
What is DeleteBuilder ?
Delete builder is a suit of classes to allow you to delete records of database in mass.
It use a where clause responding to same rules as QueryBuilder but you can specify fields to update.
Delete all records
To delete all records of a table in database, use DeleteBuilder without where clause :
$userManager = $this->entityManagerFactory
->get(UserManager::class);
$query = $userManager->createDeleteBuilder('userAlias');
$userManager->executeDelete($query);
All usernames will be deleted.
Where clause
You can use where to select records to delete.
The where clause work same as QueryBuilder.
$userManager = $this->entityManagerFactory
->get(UserManager::class);
$query = $userManager->createDleteBuilder('userAlias');
$query->where()
->firstCondition(
$query->getFieldForCondition('status'),
ConditionOperatorType::equal,
':status'
)
;
$query->setParameter('status', 'pending');
$userManager->executeUpdate($query);
Enabling triggers
By default, DeleteBuilder query skip triggers beforeDelete and afterDelete for performance purpose, but it is possible to activate them by passing false in second parameter.
class UserEntity extends AbstractEntity
implements BeforeDeleteInterface, AfterDeleteInterface
{
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 beforeDelete(): void
{
// Delete in cascade
if ($this->projects !== null) {
$this->projects->delete();
}
}
public function afterDelete(): void
{
self::numUsers--;
}
}
$userManager = $this->entityManagerFactory
->get(UserManager::class);
$query = $userManager->executeDelete();
$userManager->executeDelete($query, false);
Here, the projects of each users will be deleted too and the static property numUsers will be decrementd at each deleted user.