【问题标题】:Doctrine2 ArrayCollection count Distinct uniqueDoctrine2 ArrayCollection 计数 Distinct 唯一
【发布时间】:2020-07-08 13:52:58
【问题描述】:

我在使用 ArrayCollection Count 时遇到了一点麻烦。我不知道是否可以做我想做的事。

我有 2 个实体:

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*/
    }
}

我需要的是 Resultado->numInstancias 计数与 Instancia 实体中的字段名称不同。

在存储库中它会像下面这样,但我需要在实体中做

$qb = $em->createQueryBuilder();
   $qb->select('COUNT(I)')
      ->from('App\Entity\Instancia', 'I')
      ->where('I.resultado = xxx')
      ->groupBy('I.name');

感谢您的帮助!!

【问题讨论】:

    标签: count doctrine distinct arraycollection


    【解决方案1】:

    是的,这是可能的。您可以编写一个函数,通过过滤它们来计算 Instancias。不确定您所拥有的一切是如何设置的,因此可能需要进行一些更改:

    public function countInstancias()
    {
        return count($this->getInstnacias()->filter(function (Instancia $i) {
            return $i->getName() === 'some name';
        }));
    }
    

    把它放在你的Resultado 实体中。我使用类似的方法从某些组中获取用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多