Doctrine:确定UniqueEntity的自定义存储库不起作用

时间:2016-07-31 12:51:07

标签: php doctrine-orm symfony

为了解决problem I asked about earlier,我尝试创建一个自定义存储库函数,根据Repair {{1}确定device的实例是否唯一}}和name约束。

这是我的课程colors的学说注释。请注意Repair属性是多对一(多个修复一个设备),而device是多对多。

colors

这是我的 RepairRepository.php ,其中/** * @ORM\Table(name="repair") * @ORM\Entity(repositoryClass="AppBundle\Repository\RepairRepository") * @UniqueEntity(fields={"name", "device", "colors"}, repositoryMethod="getSimilarRepairs", message="Repair {{ value }} already exists for this name, device and colour combination.") */ 是一个数组。

$criteria['colors']

我有三个问题可能会被带回一个:

  • 编辑:每次更改,导致重复或不重复,我都会收到重复实体存在的消息。
  • 编辑:尽管出现错误消息,仍然会执行名称更改!
  • 添加:我可以创建尽可能多的重复项,但从来没有错误消息。

1 个答案:

答案 0 :(得分:0)

您的问题是颜色关系是ManyToMany。 在SQL中,您无法查询' ='关于这种关系。

这非常复杂,这就是为什么Doctrine(我们可能)不能单凭它。

构建查询的部分解决方案:

public function getSimilarRepairs(array $criteria) {
    $builder = $this->createQueryBuilder('r')
        ->where('r.device = :device')
        ->andWhere('r.name = :name')->setParameter('name',$criteria['name'])
        ->andWhere('r.colors = :colors')->setParameter('deviceid',$criteria['device']);

    // r matches only if each of your colors exists are related to r :
    $i=0;
    foreach($criteria['colors'] as $color){
        $i++;
        $builder->join('r.colors','c'.$i)->andWhere('c = :color'.$i)->setParameter('color'.$i,$color);
    }

    // Then you had also to check than there is no other color related to r :

    // I don't know how


    return $builder->getQuery();
}

但是,让我提出另一个解决方案:

在您的修复实体中,您可以存储相关颜色的副本:

/**
 * @var string
 *
 * @ORM\Column(name="name_canonical", type="string")
 */
private $serializedColors;

使用doctrine生命周期事件设置它:

/** 
* @ORM\PrePersist
* @ORM\PreUpdate 
*/
public function updateColors()
{
    $serializedColors = '';

    foreach($this->colors as $color){
        $serializedColors .= $color->getId().'#';
    }

    $this->serializedColors = $serializedColors;
}

不要忘记添加@HasLifecycleCallbacks

然后将您的UniqueEntityConstraint更改为fields={"name", "device", "serializedColors"},忘记自定义查询,它将起作用。