kikwik / doctrine-relation-count-bundle
Manage counter as database property for doctrine relations
Installs: 74
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:symfony-bundle
Requires
- php: >=8.1
- doctrine/doctrine-bundle: ^2.8
- doctrine/orm: ^2.14 || ^3.0
- symfony/framework-bundle: ^6.4|^7.0
- symfony/property-access: ^6.4|^7.0
This package is auto-updated.
Last update: 2024-12-08 20:47:11 UTC
README
Manage counter as database property for doctrine relations
Installation
- require the bundle
#!/bin/bash composer require kikwik/doctrine-relation-count-bundle
Usage
- Add an integer field in the related classes wich will contain the count value, setter is not required.
#[ORM\Entity(repositoryClass: FamigliaRepository::class)] class Famiglia { #[ORM\Column] private int $numProdotti = 0; public function getNumProdotti(): int { return $this->numProdotti; } }
#[ORM\Entity(repositoryClass: SimboloRepository::class)] class Simbolo { #[ORM\Column] private int $numProdotti = 0; public function getNumProdotti(): int { return $this->numProdotti; } }
- Add the
#[CountableEntity]
attribute on top of your child class - Add the
#[CountableRelation]
attribute on the ManyToOne or ManyToMany relations which you would count - Set the
targetProperty
parameter to the count property in the related class
use Kikwik\DoctrineRelationCountBundle\Attribute\CountableEntity; use Kikwik\DoctrineRelationCountBundle\Attribute\CountableRelation; #[ORM\Entity(repositoryClass: ProdottoRepository::class)] #[CountableEntity] class Prodotto { #[ORM\ManyToOne(inversedBy: 'prodotti')] #[CountableRelation(targetProperty: 'numProdotti')] private ?Famiglia $famiglia = null; #[ORM\ManyToMany(targetEntity: Simbolo::class, inversedBy: 'prodotti')] #[CountableRelation(targetProperty: 'numProdotti')] private Collection $simboli; }
Custom updater
If you need to use a customized query for the counter update you can define a updateCountableRelation
method in your child repository
class ProdottoRepository extends ServiceEntityRepository { public function updateCountableRelation(object $localObject, string $relationName, object $relatedObject, string $relatedProperty) { $dql = sprintf('UPDATE %s related set related.%s = (SELECT COUNT(local.id) FROM %s local WHERE local.%s = :id AND local.isActive = 1) WHERE related.id = :id', get_class($relatedObject), $relatedProperty, get_class($localObject), $relationName, ); $query = $this->getEntityManager()->createQuery($dql) ->setParameter('id', $relatedObject->getId()); $query->execute(); } }