如何在 Sylius 中自定义实体属性?

问题描述

我正在开发 Sylius 应用程序并想修改实体的属性

更具体地说:我想要实现的是使Productvariant.onHand(或实际上是数据库中的相应列)nullable

Sylius 的文档提供了一篇吉祥文章https://www.paypal.com/buttons”。但它没有描述如何更改现有属性的定义。

如何修改Productvariant.onHand 这样的 Sylius(核心)实体的属性


到目前为止我的尝试:我扩展了 Sylius\Component\Core\Model\Productvariant 并向 onHand 属性添加了 Doctrine 注释:

/**
 * @ORM\Entity
 * @ORM\Table(name="sylius_product_variant")
 */
class Productvariant extends BaseProductvariant
{
    ...
    /**
     * ...
     * @ORM\Column(type="integer",nullable=true)
     */
    protected $onHand = 0;
    ...
}

好吧,extend上课绝对是正确的一步。而且它也能正常工作:

$ bin/console debug:container --parameter=sylius.model.product_variant.class
 ------------------------------------ ----------------------------------- 
  Parameter                            Value                              
 ------------------------------------ ----------------------------------- 
  sylius.model.product_variant.class   App\Entity\Product\Productvariant  
 ------------------------------------ ----------------------------------- 

但是简单地添加属性定义导致了错误

$ ./bin/console doctrine:schema:validate
  Property "onHand" in "App\Entity\Product\Productvariant" was already declared,but it must be declared only once

解决方法

看起来 ProductVariant 在配置文件中有它的映射。

如果一个包在配置文件而不是注释中定义了它的实体映射,你可以像任何其他常规包配置文件一样覆盖它们。唯一需要注意的是,您必须覆盖所有这些映射配置文件,而不仅仅是您真正想要覆盖的那些。

https://symfony.com/doc/4.4/bundles/override.html#entities-entity-mapping

您也可以尝试使用所需的映射创建一个新实体(您需要自己添加所有列)并将 sylius.model.product_variant.class 指向这个新类。

,

实体配置可以通过添加 AttributeOverrides 注释来覆盖:

/**
 * @ORM\Entity
 * @ORM\Table(name="sylius_product_variant")
 * @ORM\AttributeOverrides({
 *     @ORM\AttributeOverride(
 *         name="onHand",*         column=@ORM\Column(
 *             name="on_hand",*             type="integer",*             nullable=true
 *         )
 *     )
 * })
 */
class ProductVariant extends BaseProductVariant
{
    ...
    /**
     * ...
     * no changes
     */
    protected $onHand;
    ...
}

相关教义文献文章: