如何覆盖 Sylius 中的产品模型?

How to override Product model in Sylius?

我正在研究 Sylius 1.2.8。我已经覆盖了产品模型并且它工作正常但是当我添加具有属性的新产品时:

<?php
...

$em = $this->container->get('sylius.manager.product');

/**
* @var \Sylius\Component\Product\Model\ProductAttributeValueInterface $attribute
* @var \Sylius\Component\Core\Model\ProductInterface $product 
*/

$product->addAttribute($attribute);
$em->persist($product);
$em->flush();

它抛出这个错误:

An exception occurred while executing 'INSERT INTO sylius_product_attribute_value (locale_code, text_value, boolean_value, integer_value, float_value, datetime_value, date_value, json_value, product_id, attribute_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["en_US", null, null, null, null, null, null, "[\"013ea12a-1aff-4050-8107-20b53ada73ce\"]", null, 28]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null

我的自定义产品模型如下所示:

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Component\Core\Model\Product as BaseProduct;

class Product extends BaseProduct implements ProductInterface
{
    public function __construct()
    {
        parent::__construct();
    }
}

还有我的配置文件:

sylius_product:
  driver: doctrine/orm
  resources:
    product:
      classes:
        repository: AppBundle\Doctrine\ORM\ProductRepository
        model: AppBundle\Entity\Product

我发现了一个类似的问题:whosebug.com/q/22919004/6248367。但这并没有解决我的问题,也没有回答应用程序失败的原因。这个答案也是 4 岁。有人可以帮我解决这个问题吗?

编辑:每当我创建新产品并同时向其添加属性时,管理员也会抛出此错误。解决方法是先创建产品,然后添加属性。

我找到问题了。正如@czende 提到的,正确检查配置。

在我的例子中,我在 subject 中设置了错误的 class 而覆盖了 attribute:

sylius_product:
  driver: doctrine/orm
  resources:
    product:
      classes:
        repository: AppBundle\Doctrine\ORM\ProductRepository
        model: AppBundle\Entity\Product

sylius_attribute:
  driver: doctrine/orm
  resources:
    product:
        # Make sure to provide the correct Product class in the subject.
      subject: AppBundle\Entity\Product 
      attribute:
        classes:
          model: AppBundle\Entity\ProductAttribute
          repository: AppBundle\Doctrine\ORM\ProductAttributeRepository

还要确保在映射配置中使用 mappedSuperclass 而不是 entity 作为 commented by Michał Marcinkowski in issue #3997

AppBundle\Entity\ProductAttribute:
  type: mappedSuperclass
  table: sylius_product_attribute

编辑:要调试错误,首先检查 symfony debug bar 中的 warnings。它可以缩小您的错误搜索范围。如果您的配置文件有问题,它也可以提示您。