Symfony. Creando un filtro para Doctrine

Aprende a añadir un filtro en todas las consultas que realices sobre una entidad

->andWhere('post.isArchived = :isArchived')
->setParameter('isArchived', false)
class Category {/**
* @ORM\OneToMany(targetEntity="Article", mappedBy="category")
*/
private Collection $articles;
}
$articles = $category->getArticles();
$firstTitle = $articles->first()->getTitle();

Creación de un filtro para Doctrine

/**
* @ORM\Column(type="boolean")
*/
private bool $isArchived;
<?phpdeclare(strict_types=1);
namespace App\Doctrine;
use App\Entity\Article;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
class ArchivedFilter extends SQLFilter
{
public function addFilterConstraint(
ClassMetadata $entity,
$targetTableAlias
) {
if ($entity->getReflectionClass()->name !== Article::class) {
return '';
}
return sprintf('%s.is_archived = false', $targetTableAlias);
}
}
if ($entity->getReflectionClass()->name !== Article::class)  {
return '';
}

Activación del filtro en Doctrine

doctrine: 
...
orm:
filters:
article_filter_archived:
class: App\Doctrine\ArchivedFilter
enabled: true

Desactivación del filtro

/** @var EntityManagerInterface $em */        
$em = $this->getDoctrine()->getManager();
$em->getFilters()->disable('soft-article_filter_archived');
/** @var EntityManagerInterface $em */        
$em = $this->getDoctrine()->getManager();
$em->getFilters()->enable('soft-article_filter_archived');

Pasando parámetros al filtro

return sprintf('%s.is_archived = false', $targetTableAlias);
return sprintf('%s.is_archived = %s', $targetTableAlias, $this->getParameter('isArchived'));
doctrine: 
...
orm:
filters:
article_filter_archived:
class: App\Doctrine\ArchivedFilter
enabled: true
parameters:
isArchived: false
/** @var EntityManagerInterface $em */        
$em = $this->getDoctrine()->getManager();
$filter = $em->getFilters()->enable('soft-article_filter_archived');
$filter->setParameter('isArchived', false');

Conclusiones

❗️ Filtros de Doctrine y Soft Delete

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store