在数组集合中按规范查找元素的最佳方法

sma*_*ius 4 symfony doctrine-orm

假设我有两个实体:

  • 实体 A:地点
  • 实体B:图像

一个位置拥有多个图像(一对多)。图像可能具有属性类型。我经常遇到一个用例,我需要按类型过滤图像。目前,我通过生命周期回调来完成此操作,如下例所示:

    /**
     * This functions sets all images when the entity is loaded
     *
     * @ORM\PostLoad
     */
    public function onPostLoadSetImages($eventArgs)
    {
        $this->recommendedForIcons = new ArrayCollection();
        $this->whatYouGetImages    = new ArrayCollection();

        foreach ($this->getImages() as $image) {

            if ('background-image' === $image->getType()->getSlug()) {
                $this->backgroundImage = $image;
            } elseif ('product-icon' === $image->getType()->getSlug()) {
                $this->mainIcon = $image;
            } elseif ('product-image' === $image->getType()->getSlug()) {
                $this->productImage = $image;
            } elseif ('recommended-icon' === $image->getType()->getSlug()) {
                $this->recommendedForIcons->add($image);
            } elseif ('what-you-get-image' === $image->getType()->getSlug()) {
                $this->whatYouGetImages->add($image);
            } elseif ('productshoot-fullcolour' === $image->getType()->getSlug()) {
                $this->productImageFullColor = $image;
            } elseif ('product-overview' === $image->getType()->getSlug()) {
                $this->productOverviewImage = $image;
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以在学说数组集合中搜索元素,而不仅仅是搜索键或元素本身。

谢谢。

Mat*_*teo 6

您可以使用回调函数过滤 ArrayCollection。作为示例,您可以在实体中实现一个方法,例如:

 public  function  getWhatYouGetImages()
 {
    return $this->getImages()->filter(
        function ($image)  {
            return  ('what-you-get-image' === $image->getType()->getSlug());
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

我建议也看看 Doctrine Criteria,如这个答案中所述。我无法为此提出一个示例,因为我不知道 Image 实体上的 getType()->getSlug() 。

希望这有帮助