Symfony 最大条目数

Symfony 最大条目数,symfony,doctrine-orm,entity,Symfony,Doctrine Orm,Entity,我有一些实体,但我想在db中验证最多X个条目。 例如,数据库中不允许超过5个类别。 我试着看看是否有什么方法可以解决我的问题,但我没有发现任何有用的方法。 提前感谢您可能需要自己实施此功能。我没见过这样的事,但你自己做一件也不难。只需添加一个函数来检查数据库中有多少条目,并在插入任何内容之前调用此函数 可以这样做: public function newAction(){ $isAllowed = $this->checkMaxRecords(); if($isAllow

我有一些实体,但我想在db中验证最多X个条目。 例如,数据库中不允许超过5个类别。 我试着看看是否有什么方法可以解决我的问题,但我没有发现任何有用的方法。
提前感谢

您可能需要自己实施此功能。我没见过这样的事,但你自己做一件也不难。只需添加一个函数来检查数据库中有多少条目,并在插入任何内容之前调用此函数

可以这样做:

public function newAction(){
    $isAllowed = $this->checkMaxRecords();

    if($isAllowed){
        //save to the database
    }
}

private function checkMaxRecords(){
    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
       'SELECT c
        FROM AcmeStoreBundle:Category c'
    );

    $category = $query->getResult();

    if(count($category) >= 5){
        return false;
    }
    return true;
}

这是未经测试的代码,但沿着这些思路应该可以让您走上正确的轨道。

如果您需要在多个位置验证您的实体或对多个实体类执行此类验证,您可以编写自定义验证约束来执行此操作。这确实感觉有点过分,但从技术上讲,这是“正确”的解决方案。这在中的Symfony手册中有记录。例如:

约束类:

<?php

namespace Your\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class MaxEntries extends Constraint
{
    public $message = 'The maximum %max% %name% entries already exist.';
    public $max = 5;

    public function validatedBy()
    {
        return 'maxEntries';
    }

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}
validation.yml:

Your\Bundle\YourEntity:
    constraints:
        - Your\Bundle\Validator\Constraints\MaxEntries:
            # You can override the default constraint attributes here
            message: "Failed! The maximum %max% %name% entries already exist."
            max: 42

注意,您可能会想出一个比MaxEntries更好的名称(我通常会花更多时间思考最有意义的名称)。此外,validator类当前不包含将其应用于非条令实体的类的保护。

谢谢,但这不是我想要做的。我在验证约束中直接思考。我甚至没有在为预科生准备的条令监听器中思考:(可能是一个使用回调验证(@Assert\callback)的解决方案)…太好了,这就是我一直在寻找的。我还没有测试它,但谢谢!
validator.max_entries:
    class: Bullitt\TargetNeutral\SpectatorBundle\Validator\Constraints\MaxEntriesValidator
    arguments:    [@doctrine.orm.entity_manager]
    tags:
        - { name: validator.constraint_validator, alias: maxEntries }
Your\Bundle\YourEntity:
    constraints:
        - Your\Bundle\Validator\Constraints\MaxEntries:
            # You can override the default constraint attributes here
            message: "Failed! The maximum %max% %name% entries already exist."
            max: 42