【问题标题】:How to customize an entity property in Sylius?如何在 Sylius 中自定义实体属性?
【发布时间】:2021-06-08 16:09:22
【问题描述】:

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

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

Sylius 的文档提供了一篇吉祥的文章“Customizing Models”。但它没有描述如何更改现有属性的定义。

如何修改 Sylius(核心)实体的属性,例如 ProductVariant.onHand


到目前为止我尝试了什么:我扩展了 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

【问题讨论】:

标签: symfony model doctrine entity sylius


【解决方案1】:

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

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

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

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

【讨论】:

  • 欢迎使用 StackOverflow! ) 谢谢您的回答。我通过添加 Attribute Override 注释覆盖了实体配置。它可以工作,但最好在配置中覆盖它。该怎么做?
  • 属性覆盖可能很难看,但它有效 :) 您可以创建一个新实体并设置 sylius.model.product_variant.class: App\Entity\MyClass
【解决方案2】:

可以通过添加 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;
    ...
}

相关教义文档文章:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多