Symfony 4:从实体中删除集合

问题描述 投票:0回答:1

我有一个产品实体和产品图片实体。我只想对产品实体使用软删除,然后对产品图片实体进行删除。软删除工作正常。删除产品时,deleted_at列设置为当前时间。因此,我想在delete_at列更新时删除产品图片。我想知道是否可以在实体类中直接做到这一点?以及如何?

我尝试在setDeletedAt函数中进行集合定义的产品实体。

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ProductImage", mappedBy="product", orphanRemoval=true, cascade={"persist"})
     */
    private $productImages;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $deleted_at;

    public function __construct()
    {
        $this->productImages = new ArrayCollection();
    }

    public function setDeletedAt(?\DateTimeInterface $deleted_at): self
    {
        // Here I try to remove images when deleted_at column is updated
        $productImage = $this->getProductImages();
        $this->removeProductImage($productImage);

        $this->deleted_at = $deleted_at;
        return $this;
    }

    /**
     * @return Collection|ProductImage[]
     */
    public function getProductImages(): Collection
    {
        return $this->productImages;
    }

    public function addProductImage(ProductImage $productImage): self
    {
        if (!$this->productImages->contains($productImage)) {
            $this->productImages[] = $productImage;
            $productImage->setProduct($this);
        }

        return $this;
    }

    public function removeProductImage(ProductImage $productImage): self
    {
        if ($this->productImages->contains($productImage)) {
            $this->productImages->removeElement($productImage);
            // set the owning side to null (unless already changed)
            if ($productImage->getProduct() === $this) {
                $productImage->setProduct(null);
            }
        }
        return $this;
    }
}

但是当我进行软删除时,将调用setDeletedAt()并返回以下错误:

Argument 1 passed to App\Entity\Product::removeProductImage() must be an instance of App\Entity\ProductImage, instance of Doctrine\ORM\PersistentCollection given, called in ...

感谢您的帮助!

---- UPDATE ----

John提供的解决方案很好:

foreach ($this->getProductImages() as $pi) {
    $this->removeProductImage($pi);
}

谢谢!

symfony collections entity relation
1个回答
0
投票

很容易解释的错误:

至此:

    $productImage = $this->getProductImages();
    $this->removeProductImage($productImage);

您正在传递一个集合,而不是一个ProductImage对象。

要全部删除,只需执行:

foreach ($this->getProductImages() as $pi) {
    $this->removeProductImage($pi);
}
© www.soinside.com 2019 - 2024. All rights reserved.