CakePHP2 验证字段不在 table

CakePHP2 validation on field not in table

我在 table 中有 4 个属性; num_anum_bnum_cnum_d,这些分别可以在0到2的范围内,例如我在我的 $validate 属性 模型中有:

'num_a' => [
  'numeric' => [
    'rule' => 'numeric',
    'message' => 'Please provide the number of a.',
  ],
 'isInRange' => [
   'rule' => ['range', -1, 3],
   'message' => 'Must be between 0 and 2.'
 ],

我面临的问题是它们的总和必须大于 0。如果是这种情况,我希望 return 出现一些验证错误,例如:

'num_all' => [
  'rule' => 'returnFalse',
  'message' => 'There were no a, b, c or d selected.',
],

我的模型中有 returnFalse 函数,它只是

public function returnFalse() {
  return false;
}

始终添加此规则。

beforeValidate 中,我正在检查 num_anum_d 的总和,如果 $sum > 0 像这样删除验证规则:

public function beforeValidate($options=array())
{
  $sum = 0;
  $sum += (isset($this->data['MyModel']['num_a'])) ? $this->data['MyModel']['num_a'] : 0;
  $sum += (isset($this->data['MyModel']['num_b'])) ? $this->data['MyModel']['num_b'] : 0;
  $sum += (isset($this->data['MyModel']['num_c'])) ? $this->data['MyModel']['num_c'] : 0;
  $sum += (isset($this->data['MyModel']['num_d'])) ? $this->data['MyModel']['num_d'] : 0;

  if ($sum > 0) {
    $this->validator()->remove('num_all');
  }
}

但出于某种原因,我无法将其变为 return num_all 的验证错误。

我什至尝试添加一个虚拟字段,所以验证错误可能有一些附加到:

public $virtualFields = [
  'num_all' => 'SELECT 0 FROM dual',
];

但这也没有用。我正在使用 CakePHP v2.8。

好的,所以我放弃了 $validate 属性 和虚拟字段等中的 num_all 以及 'always fails' 规则,而是对条目进行了黑客攻击到 beforeValidate 中的模型 validationErrors 数组:

public function beforeValidate($options=array())
{
  $sum = 0;
  $sum += (isset($this->data['MyModel']['num_a'])) ? $this->data['MyModel']['num_a'] : 0;
  $sum += (isset($this->data['MyModel']['num_b'])) ? $this->data['MyModel']['num_b'] : 0;
  $sum += (isset($this->data['MyModel']['num_c'])) ? $this->data['MyModel']['num_c'] : 0;
  $sum += (isset($this->data['MyModel']['num_d'])) ? $this->data['MyModel']['num_d'] : 0;

  if ($sum > 0) {
    $this->validationErrors['num_all'][] = 'There were no a, b, c or d selected.'
  }
}

现在可以正常使用了。希望这有帮助。