2017-08-14 92 views
0

我有2个表OrdersProducts。在orders表中有外键product_id。有时,订单不一定包含产品(没有任何产品ID的订单是允许的)。在这种情况下,我存在导致问题保存数据的验证规则。cakePHP验证existsIn()为空/空字段,如何摆脱...?

$rules->add($rules->existsIn(['product_id'], 'Products')); //Validation in the model of Orders. 

N.B. - 请记住,我已允许product_id在我的数据库中为空。

回答

1

编辑:根据ndm exists的评论existsIn检查null或存在应该是existsIn的默认功能,如果您的列在数据库中可为空。如果它不起作用,或许你意外地传递了某种价值,或者你的专栏没有被列为可空。

你也应该能够覆盖存在于允许这个或其他条件。基本上你会指定一个存在或它是一个特定的值。在这种情况下,null。

回答How to build rule exist in or equal to a number in cakephp 3?

$rules->add(
function ($entity, $options) { 
    $rule = new ExistsIn(['product_id'], 'Products'); 
    return $entity->product_id === NULL || $rule($entity, $options); 
}, 
    ['errorField' => 'product_id', 'message' => 'Product ID specified but does not exist'] 
); 
+1

通常修改,承认'null'应开箱的(因为在DB列可以为空)。 ** HTTPS://github.com/cakephp/cakephp/blob/3.4.12/src/ORM/Rule/ExistsIn.php#L113** – ndm