【问题标题】:How to override Product model in Sylius?如何在 Sylius 中覆盖产品模型?
【发布时间】:2018-11-10 12:03:37
【问题描述】:

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

<?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();

它会抛出这个错误:

执行“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) 值 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' 带参数 ["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

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

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

【问题讨论】:

  • 我已经尝试过全新安装您的 Sylius 版本并添加完全相同的配置并且工作正常。您还有其他需要覆盖的东西吗?从头开始尝试一切 - resource.yml、扩展 BaseProduct 的产品实体、扩展 BaseProductRepository 的产品存储库和正确的 Product.orm.yml 配置。
  • 您似乎需要在添加属性之前设置产品,因为尚未设置产品 ID。所以在持久化属性之前先持久化产品
  • @PuyaSarmidani 你是对的,但教义应该在内部自动管理。根据您的说法,如果这是预期的行为,那么管理员的产品创建是如何中断的?
  • @czende 我认为你是对的,但我还没有足够的时间检查所有配置。我会尽快回复。

标签: symfony sylius


【解决方案1】:

我已经找到了问题所在。正如@czende 所说,正确检查配置。

就我而言,我在覆盖attribute 时在subject 中设置了错误的类:

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 由Michał Marcinkowski 在问题#3997 中使用

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多