【问题标题】:Symfony 4.1 : UniqueEntity validation on ArrayCollectionSymfony 4.1:ArrayCollection 上的 UniqueEntity 验证
【发布时间】:2018-12-10 09:52:38
【问题描述】:

我有一个父实体Product,怎么可能在多个Family中。

Family 属性显示为 CollectionType。目的是创建尽可能多的系列,但每个系列的名称对于产品来说必须是唯一的。

当我在族表中有数据时,它工作正常;但是当它是空的并且我一次为我的产品添加两个同名的系列时,@UniqueEntity 不会被触发;否则就是 ORM uniqueConstraints 如何响应。

执行“INSERT INTO”时发生异常 家庭(名称,max_product,必需,created_at, updated_at,promotion_id) VALUES (?, ?, ?, ?, ?, ?)' with params ["toto", 1, 0, "2018-12-06 14:54:13", "2018-12-06 14:54:13", 1]:

下面是我的实体样本:

/**
 * @var Family[]|ArrayCollection
 *
 * @ORM\OneToMany(targetEntity=Family::class, mappedBy="product", fetch="LAZY", cascade={"persist", "remove"}, orphanRemoval=true)
 * @ORM\OrderBy({"id" = "ASC"})
 * @Assert\Valid
 */
private $families;

/**
 * @ORM\Entity(repositoryClass=ProductCollectionFamilyRepository::class)
 * @ORM\Table(name="product_collection_family",
 *     indexes={@ORM\Index(name="IDX_FAMILY_NAME", columns={"name"})},
 *     uniqueConstraints={
 *        @ORM\UniqueConstraint(columns={"promotion_id", "name"})
 *    }
 * )
 *
 * 2.5.4.5RG02
 *
 * @UniqueEntity(
 *     fields={"product", "name"},
 *     errorPath="name",
 *     message="backend.error.label.family.unique_entity"
 * )
 */
class Family
{
    use TimestampableEntity;
    use ProductCollectionTrait;

    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank
     * @Assert\Length(min="1", max="100", minMessage="backend.error.label.short", maxMessage="backend.error.label.long")
     */
    private $name;

   /**
    * @var Product
    *
    * @ORM\ManyToOne(targetEntity=Product::class, inversedBy="families", fetch="LAZY")
    * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
    * @Assert\NotBlank
    */
   private $product;
}

有什么想法吗?

【问题讨论】:

  • 在 2 个字段上使用 UniqueEntity 使其唯一,但在两个字段中不是一个,因此如果您输入产品 A,名称 B 产品 A,名称 C,则不会触发约束。不是你的问题吗?
  • 但这不是 uniqueEntity 错误。唯一实体错误消息应该是这样的 SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  • @hous 实际上我忘记了部分消息,我也收到了这条消息:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '7-test' for key 'UNIQ_E346EBFE139DF1945E237E06'
  • @Robert 当我一次添加两个或更多家庭时出现问题(这是一个 CollectionType 表单)。目的是使产品不具有相同的姓氏。当我一个一个添加时,就可以了;但不是当我一次尝试所有的时候。
  • 那么您可以使用表单验证,不是吗? :)

标签: php symfony validation symfony-forms symfony4


【解决方案1】:

为了做到这一点,我只是创建了一个断言回调函数来检查数组集合中的元素,然后构建一个违规。

/**
 * @Assert\Callback
 *
 * @param ExecutionContextInterface $context
 * @param $payload
 */
public function validate(ExecutionContextInterface $context, $payload)
{
    $productFamilies = clone $this->getProductFamilies();
    $productFamiliesFiltered = $this->getProductFamilies()->filter(function ($currentProductFamily) use ($productFamilies) {
        // Remove current family from original collection
        $productFamilies->removeElement($currentProductFamily);
        foreach ($productFamilies as $data) {
            //we have same name ?
            if ($currentProductFamily->getName() === $data->getName()) {
                return true;
            }
        }

        return false;
    });

    if (0 !== $productCollectionFiltered->count()) {
        $context->buildViolation('backend.error.label.product_family.unique_entity')
            ->atPath('productFamilies')
            ->addViolation();
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多