kikwik/doctrine-relation-count-bundle

Manage counter as database property for doctrine relations

v1.0.2 2024-06-08 19:51 UTC

This package is auto-updated.

Last update: 2024-11-08 20:36:04 UTC


README

Manage counter as database property for doctrine relations

Installation

  1. 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();
    }
}