CakePHP 3 验证两列中的唯一性

CakePHP 3 Validate unique within two columns

我有 table 个产品尺寸

Product Details
id  product_id size
1       1        m
1       1        l
2       2        l

如果我尝试向尺寸为 m 的产品 1 添加另一个细节,它应该 return false 但对于尺寸为 m 的产品 2 应该通过

在我的产品详情中Table这里是验证器它的东西

 //Product Detail Table
public function validationDefault(Validator $validator){
$validator
        ->add('size', 'unique', ['rule' => 'validateUnique', 'provider' => 'table'])

不确定如何为列添加条件

这就是 scope 选项的用途,它允许您向唯一性约束添加其他字段。

Unique validation can be scoped to the value of another column:

$validator->add('email', [
    'unique' => [
        'rule' => ['validateUnique', ['scope' => 'site_id']],
        'provider' => 'table'
    ]
]);

In the above example, the email uniqueness will be scoped to only rows having the same site_id. Scoping will only be used if the scoping field is present in the data to be validated.

API > \Cake\ORM\Table::validateUnique()

但是,这至少应该是一个应用程序规则,因为它容易出现竞争条件,因此需要在交易中进行检查,默认情况下,这只发生在应用程序规则中。

您可以使用内置的 IsUnique 规则,只需将多个列名传递给该规则即可。

use Cake\ORM\RulesChecker;

// ...

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['product_id', 'size']));

    return $rules;
}

另见