我已经以这种方式使用UniqueEntity:
/**
* @ORM\Entity()
* @ORM\Table(name="benefit_group_category")
* @UniqueEntity(fields={"name", "project"}, ignoreNull=false, message="Duplicated group category for this project")
*/
我已经知道如何使用它。
在另一种情况下,我需要做以下操作:
* @UniqueEntity(fields={"entityId", "status"}, message="There is already a Quality Review Pending for this entity")
但需要指出,对于相同的
entityId
如果status == 1
,则不允许有重复项,但如果status == 0
,则应该通过验证。基本上,例如,我可以有任意数量的记录,其中
entityId = 37
并且status = 0
,但只有一个status = 1
。这是可能的吗?
编辑:请在此处找到更新后的版本,以进行二次检查。 在我的原始问题中,我忘记提及另一个参数(entityName),但这并不改变其本质。
存储库类
<?php
namespace AppBundle\Entity;
/**
* QualityReviewRequestRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class QualityReviewRequestRepository extends \Doctrine\ORM\EntityRepository
{
/**
* @param array $criteria
* @return array
*/
public function getByEntityIdAndEntityNameAndStatusCriteria(array $criteria)
{
// Todo remove this first return, it's done on purpose to force the system to throw an error, but it doesn't.
return $this->createQueryBuilder('e')
->andWhere('e.entityId = :entityId')
->setParameter('entityId', $criteria['entityId'])
->getQuery()
->getResult()
;
if (QualityReviewRequest::STATUS_NEW == $criteria['status']) {
return $this->createQueryBuilder('e')
->andWhere('e.entityId = :entityId')
->setParameter('entityId', $criteria['entityId'])
->andWhere('e.entityName = :entityName')
->setParameter('entityName', $criteria['entityName'])
->andWhere('e.status = :status')
->setParameter('status', $criteria['status'])
->getQuery()
->getResult()
;
}
return [];
}
}
主类:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* QualityReviewRequest
*
* @ORM\Table(name="quality_review_requests")
* @ORM\Entity(repositoryClass="AppBundle\Entity\QualityReviewRequestRepository")
* @UniqueEntity(fields={"entityId","entityName","status"}, repositoryMethod="getByEntityIdAndEntityNameAndStatusCriteria", message="There is already a Quality Review Pending for this entity")
*/
class QualityReviewRequest
{
const STATUS_NEW = 0;
const STATUS_DONE = 1;
use TimestampableEntity;
// removed useless stuff
/**
* @var string
*
* @ORM\Column(name="entityName", type="string", length=255)
*/
private $entityName;
/**
* @var integer
*
* @ORM\Column(name="entityId", type="integer")
*/
private $entityId;
// More stuff
}