php - 如果字段为空,则在以嵌入形式编辑父实体时删除子实体 - Symfony 4

标签 php database symfony doctrine-orm one-to-one

我正在使用 symfony 4,我有两个实体;产品和产品图像。我在两者之间创建了 OneToOne 关系,并将 ProductImageType 表单嵌入到我的 ProductType 表单中,因为一个产品有一个图像。我在 ProductType 表单中嵌入的字段是属于 ProductType 实体的“url”。

如果我将图像 url 留空,则在创建新产品时,这一切都按预期工作,然后不会在 ProductImage 表中创建记录。如果我提供一个 url,则会创建一条记录。但是,如果我编辑具有图像 url 的产品并删除图像 url,则会出现错误。我希望的是,相关的 ProductImage 实体将在其 url 字段上设置为 null 或更好,相关的子 ProductImage 将完全从数据库中删除。我收到的错误是:

在属性路径“url”处给出类型为“string”的预期参数,“NULL”。

我不明白这是怎么回事,因为 ProductImage 的 url 字段允许为空。解决这个问题的最佳方法是什么?非常感谢任何帮助!

产品编号:

/**
 * @ORM\OneToOne(targetEntity="App\Entity\ProductImage", mappedBy="product", cascade={"persist", "remove"})
 */
private $image;

public function getImage(): ?ProductImage
{
    return $this->image;
}

public function setImage(ProductImage $image): self
{
    $this->image = $image;

    if ($this !== $image->getProduct()) {
        $image->setProduct($this);
    }

    return $this;
}

产品图片代码:

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private $url;

/**
 * @ORM\OneToOne(targetEntity="App\Entity\Product", inversedBy="image", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
 * @Assert\Type(type="App\Entity\Product")
 */
private $product;

public function getProduct(): ?Product
{
    return $this->product;
}

public function setProduct(Product $product): self
{
    $this->product = $product;

    return $this;
}

ProductImageType代码:

->add('url', TextType::class, [
    'label' => 'Image Url',
        'attr' => [
            'placeholder' => 'A url to the image of this Product.'
        ]
    ]);

产品类型代码:

->add('image', ProductImageType::class, [
    'required' => false,
])

最佳答案

ProductImage 实体中的 SetUrl 缺少“?”在“字符串”之前。

public function setUrl(?string $url): self
{
    $this->url = $url;

    return $this;
}

关于php - 如果字段为空,则在以嵌入形式编辑父实体时删除子实体 - Symfony 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54864582/

相关文章:

php - mysql 查询未返回正确的百分比

php - 使用php将csv文件导入mysql数据库

php - WordPress页面不保存,此错误是什么意思?

php - 每个 Action 中的线条相同 - 我应该让他们这样做吗? - 交响乐2

javascript - 将变量 $ 发送到上传的 php 脚本

php - 循环,比较多个表值

mysql - 错误 1288 : The target table is not updatable in MySQL trigger

database - 如何在 NoSQL 环境中创建以下数据结构

symfony - 清除 :cache command 的 --no-debug 参数究竟是做什么的

symfony - symfony2.4 中的 Behat 3(学说访问)