Symfony 4 - UniqueEntity:我希望几家公司可以对一项服务使用相同的名称,但一家公司不能有两项具有相同名称的服务

Symfony 4 - UniqueEntity : I want that several companies may use the same name for a service but a company can't have two services with the same name

在我的 symfony 项目中,我有一个 groupValidators 实体,用于通过指示服务名称和用户在公司内创建服务...

GroupeValidateurs.php:

<?php

namespace App\Entity;

use Cocur\Slugify\Slugify;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\GroupeValidateursRepository")
 * @ORM\HasLifecycleCallbacks()
 *  @UniqueEntity(
 *  fields = {"nom"},
 *  message = "Ce nom a déjà été utilisé"
 * )
 */
class GroupeValidateurs
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * Nom du service
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $nom;

    /**
     * Liste des utilisateurs membres du service
     * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="groupe")
     */
    private $users;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $slug;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Validateur", mappedBy="groupeValidateurs", orphanRemoval=true, cascade={"persist", "remove"})
     * @ORM\OrderBy({"ordre" = "ASC"})
     */
    private $validateurs;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="services")
     * @ORM\JoinColumn(nullable=true)
     */
    private $entreprise;

并且我希望一家公司不能两次输入相同的服务名称(因此我的@UniqueEntity),但我仍然希望不止一家公司对一项服务使用相同的名称。例如,公司 A 可以有一个名为 "Commerce" 的服务,公司 B 也可以。 我怎么能那样做?因为目前,如果一家公司试图创建一个名称已用于另一家公司的服务的服务,我有我的约束干预

在 class 名字中使用法语时要小心。人们可能会认为您在这里谈论的是 Validator,但事实并非如此。我建议您将 class GroupeValidateurs 重命名为 DivisionDepartmentService。此外,当您使用 class 名称时,请使用单数。

您需要做的是添加一个约束以确保您不会多次使用相同的服务名称。你用你的注释正确地完成了那部分。

那么你想要:

  • 一家公司提供一项服务
  • 一项服务可以关联多家公司

所以你的问题就在这里

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="services")
 * @ORM\JoinColumn(nullable=true)
 */
private $entreprise;

您需要在这里使用OneToMany,因为一项服务可能与许多公司相关

编辑:我可能误读了你的问题我没有看到你似乎希望一家公司不能提供一项服务而是两项服务。对于这部分,我们需要您提供您的公司 class.

假设您在该实体中拥有公司 ID 和服务名称,您可以在 table 定义中的两列上使用唯一约束:

/**
 *
 * @Table(name="GroupeValidateurs", 
 *    uniqueConstraints={
 *        @UniqueConstraint(name="service_entreprise", 
 *            columns={"service", "entreprise"})
 *    }
 * )
 */