【问题标题】:Doctrine2 Unique Validation with multiple fieldsDoctrine2 具有多个字段的唯一验证
【发布时间】:2014-03-15 13:18:47
【问题描述】:

我有一个实体Booking,它与User 具有多对一的关系。 每个Booking 实体都有一个date 字段,该字段对于用户来说应该是唯一的。

例如,条目可能如下所示:

+----------+---------+
|   date   | user_id |
+----------+---------+
| 12-04-88 |       1 |
| 13-04-88 |       1 |
| 12-04-88 |       2 |
+----------+---------+

但不是这样的:

+----------+---------+
|   date   | user_id |
+----------+---------+
| 12-04-88 |       1 |
| 12-04-88 |       1 |
+----------+---------+

添加Booking实体的代码如下,使用ZF2 REST控制器:

输入过滤器

class BookingFilter extends InputFilter
{

    //TODO: Get from module config
    protected $config = array(
        'date-format'   => 'd-m-Y',
        'start-min'     => '07:00',
        'start-max'     => '10:00',
        'end-min'       => '16:00',
        'end-max'       => '19:00',
        'step'          => '900', //15 x 60 - 15 Min's
    );

    public function init()
    {

        $this->add(
            array(
                'name'      => 'date',
                'required'  => true,
                'validators' => array(
                    array(
                        'name'      => 'Date',
                        'options'   => array(
                            'format' => 'd-m-Y',
                        ),
                    ),
                ),
            )
        );

        $this->add(
            array(
                'name'      => 'startTime',
                'required'  => true,
                'filters'   => array(
                    array('name' => 'StringTrim')
                ),
                'validators' => array(
                    array(
                        'name'      => 'Date',
                        'options'   => array(
                            'format' => 'H:i',
                        ),
                    ),
                    array(
                        'name'      => 'GreaterThan',
                        'options'   => array(
                            'min'       => $this->config['start-min'],
                            'inclusive' => true,
                        ),
                    ),
                    array(
                        'name'      => 'LessThan',
                        'options'   => array(
                            'max'       => $this->config['start-max'],
                            'inclusive' => true,
                        ),
                    ),
                    array(
                        'name'      => 'DateStep',
                        'options'   => array(
                            'format'    => 'H:i',
                            'baseValue' => $this->config['start-min'],
                            'step'      => new \DateInterval("PT{$this->config['step']}S"),
                        ),
                    ),

                ),
            )
        );

        $this->add(
            array(
                'name'      => 'endTime',
                'required'  => true,
                'filters'   => array(
                    array('name' => 'StringTrim')
                ),
                'validators' => array(
                    array(
                        'name'      => 'Date',
                        'options'   => array(
                            'format' => 'H:i',
                        ),
                    ),
                    array(
                        'name'      => 'GreaterThan',
                        'options'   => array(
                            'min'       => $this->config['end-min'],
                            'inclusive' => true,
                        ),
                    ),
                    array(
                        'name'      => 'LessThan',
                        'options'   => array(
                            'max'       => $this->config['end-max'],
                            'inclusive' => true,
                        ),
                    ),
                    array(
                        'name'      => 'DateStep',
                        'options'   => array(
                            'format'    => 'H:i',
                            'baseValue' => $this->config['end-min'],
                            'step'      => new \DateInterval("PT{$this->config['step']}S"),
                        ),
                    ),

                ),
            )
        );

        //notes
        $this->add(
            array(
                'name'      => 'notes',
                'required'  => false,
                'filters'   => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim')
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 512,
                        ),
                    ),
                ),
            )
        );
    }
} 

控制器动作

public function create($data)
{

    $user    = $this->zfcUserAuthentication()->getIdentity();
    $booking = $this->getTimeBookingService()->validateBooking($data, $user);
        
    $booking->setUser($user);
    //some other stuff
    //persist
}

服务

public function validateBooking(array $data, UserInterface $user, Booking $booking = null)
{
    $filter = $this->getInputFilter();
    $filter->setData($data);

    if (!$filter->isValid()) {
        $this->messages = $filter->getMessages();
        return false;
    }

    if (!$booking) {
        $booking = new Booking;
    }
    $this->getDoctrineHydrator()->hydrate($filter->getValues(), $booking);

    //if this is a new booking - not an update
    if (!$booking->getId()) {
        $row = $this->bookingRepository->findOneBy(array('date' => $booking->getDate(), 'user' => $user));
        if (is_object($row)) {
            //user already has booking for this date
            $this->messages['date'] = array('This user already has a booking for this date');
            return false;
        }
    }

    return $booking;
}

问题

如何使用默认的 Doctrine 验证器或自定义的 Doctrine/ZF2 验证器来做到这一点?

我不喜欢我的方法,好像我在复制 Validator 组件的工作,但是,我上次尝试时无法让它与 Doctrine Unique Validator 一起工作,因为有超过 1 个字段必须是唯一的。

我正在考虑扩展 Doctrine Unique 验证器,它依赖于 User,它将被注入一个构造,然后扩展 validate 方法以使用 date 和 user 字段搜索存储库?

【问题讨论】:

    标签: php validation doctrine-orm zend-framework2


    【解决方案1】:

    我正在考虑扩展 Doctrine Unique 验证器 对将被注入构造的用户的依赖,然后 扩展验证方法以使用两个日期搜索存储库 和用户字段?

    对模型添加一些更改,可以将date和user_id主键设置在一起:

    /** @Id @Column(type="integer") */
    private $id;
    /** @Id @Column(type="date") */
    private $date;
    

    我不知道你的框架控制器如何持久化对象,但你可以这样做:

    try
    {
       $booking = new Booking(1, '12-19-2000');
       em->persist($booking);
       em->flush();
    }
    catch( \Doctrine\DBAL\DBALException $e )
    { 
        /* the error 23000 should print the unique constrains mysql error */
        if( $e->getPrevious()->getCode() === '23000' ) 
        { 
            echo "entity already exists";
        }
    } 
    

    【讨论】:

    • 谢谢,明天去看看,我的框架是ZF2,我希望使用\DoctrineModule\Validator\UniqueObject组件。
    • 刚刚尝试过,遇到了here 概述的问题。看起来 Doctrine2 不支持将 DateTime 对象作为 id。我会尝试解决方案并接受它是否有效:)
    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 2019-06-08
    • 2023-03-20
    • 2017-05-29
    • 2015-12-07
    • 2018-04-28
    • 2019-03-24
    相关资源
    最近更新 更多