为CakePHP中的连接表列创建验证规则

时间:2014-01-08 17:36:04

标签: php mysql sql cakephp

我在与链接表( ingredients_recipes )连接的CakePHP中的两个表(食谱和成分)之间存在 hasAndBelongsToMany 。< / p>

我的 ingredients_recipes 表有一个金额列,以便保存配方的成分值,但我不知道如何或在哪里创建验证规则只允许该列中的数字。

我已经在这里和文档中查看,但我什么也没找到。
如果您需要更多信息,请告诉我 Thnks

2 个答案:

答案 0 :(得分:1)

如果要在连接表上存储其他字段,则必须显式处理连接表,而不是在hasAndBelongsToMany中处理,其中CakePHP负责后台的连接表,因此验证规则应该在ingredients_recipes上。

顺便说一下,这种关系被称为hasManyThrough,基本上只是表达为食谱hasMany ingredients_recipes和ingredients_recipes有很多成分。

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model

答案 1 :(得分:0)

在Recipe.php和Ingredient.php模型中创建验证规则,示例如下所示:

第1步:打开Ingredient.php

第2步:编辑Ingredient.php

Class Ingredient extends AppModel{
    var $name = 'Ingredient';
    public $validate = array(
      'ingredients_recipes' => array(
        'rule'    => 'numeric',
        'message' => 'Please supply the number of ingredients recipes.'
       )
    );
}

第3步:保存并执行您的代码。

现在您的Ingredient模型验证ingredients_recipes的数字版本,如果失败则返回“消息”。

同样可以为其他模型创建多个验证规则。

对于参考:http://book.cakephp.org/2.0/en/models/data-validation.html