I'm facing a litte trouble with an ArrayCollection Count. I don't know if it is possible to do what I want.
I have 2 entities:
class Instancia{
/**
* @ORM\Column(name="name", type="string")
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Resultado", inversedBy="instancias", fetch="EXTRA_LAZY")
* @ORM\JoinColumn(name="resultado", referencedColumnName="id")
*/
private $resultado;
}
class Resultado{
public function __construct() {
$this->instancias = new ArrayCollection();
}
/**
* @ORM\OneToMany(targetEntity="App\Entity\Instancia", mappedBy="resultado", fetch="EXTRA_LAZY")
*/
private $instancias;
/**
* @ORM\Column(name="numInstancias", type="integer")
*/
private $numInstancia;
function setNumInstancias(){
$this->numInstancias = $this->instancias->count(); /*return the count of all instancias*/
/* 1) Want to count with a Distinct instancias->name*/
/* 2)or want to count with a substr filter in the instancias->name*/
}
}
What I need is that Resultado->numInstancias count do a distinct by the field name in the Instancia Entity.
In a Repository it would by like the following, but I need to do in the Entity
$qb = $em->createQueryBuilder();
$qb->select('COUNT(I)')
->from('App\Entity\Instancia', 'I')
->where('I.resultado = xxx')
->groupBy('I.name');
Thanks for your help!!
Yes, this is possible. You can write a function that counts the Instancias by filtering them. Not sure exactly how everything you have is set up so some changes might be required:
Put this in your
Resultadoentity. I use something similar to get users from certain groups.