【问题标题】:cakephp 2.x limit the number of records(behavior or model callback method)when add new recordcakephp 2.x 添加新记录时限制记录数(行为或模型回调方法)
【发布时间】:2015-04-30 08:42:58
【问题描述】:

我是 cakephp 的新手,我从来没有写过行为。 所以我需要限制模型的记录数,我知道它必须用 beforeSave 完成

模型:文档 |文档类型。文档->文档类型 我在 DocumentType 中存储了最大数量的文档。

这就是为什么我有点困惑我究竟需要模型行为或模型的回调方法(beforeSave)。 但我不知道这将如何与这两个模型一起工作。我开始了这种行为:

     class LimiteBehavior extends ModelBehavior
       {
       public function beforeSave(Model $Model,$options=array())
                    {

}

我叫这个模型:

public $actsAs=array('Limite');

这是对的还是我应该在这里传递额外的信息?

但现在我很困惑,因为我现在不知道如何在行为中使用不同的模型。

我要数一下 Document 模型记录的数量:

$this->Document->find('count')

我必须检查 DocumentType 的最大数量:

$this->DocumentType->find->('first',array('fields'=>array('max_record')))

现在我必须在 Behavior.But 中进行比较。但我不知道该怎么做。 请帮忙。

更新1: 当max_record字段与当前记录数相等时,我不想让用户更多插入新记录

【问题讨论】:

  • 这个问题对你的行为的要求不是很清楚。请您澄清一下您的预期行为是什么?
  • 我指定了目的
  • 通过您的编辑,您正在查看验证规则。
  • Excusme DavidYell,但我试图通过验证进行验证。我不知道如何制作它,因为但是,我必须限制它不适合任何文档模型字段的文档模型,只有记录计数。但这取决于 DocumentType:max_number 字段。因此,我不能申请文档字段验证:在我的情况下,$ 检查将是: $this->Document->find('count')==$this->DocumentType->find->('first' ,array('fields'=>array('max_record')))

标签: cakephp cakephp-2.0


【解决方案1】:

我建议在您的模型中创建自定义验证规则。此验证规则可能会根据您的条件检查项目的数量,并且无法根据该规则保存。

Read more about custom validation methods in the book.

我会尝试制定这样的规则,

<?php
class Document extends AppModel {

    public $validate = array(
        'document_type_id' => array(
            'rule' => 'limitDuplicates',
            'message' => __('Maximum number of documents of this type already created')
        )
    );

    public function limitDuplicates($check) {
        $max = $this->DocumentType->field('max_record', ['DocumentType.id' => $check['document_type_id']]);
        $count = $this->DocumentType->find('count', [
            'conditions' => [
                'DocumentType.id' => $check['document_type_id']
            ]
        ]);

        return $count < $max;
    }
}

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 2015-06-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多