在 CakePHP 中保存时如何验证关联模型是否存在

How to validate if associated Model exists when saving in CakePHP

假设我有一个与 'Customer' 模型关联的 'Order' 模型。

class Order {
   var $belongsTo = array('Customer');
}

CakePHP 中是否有标准方法来验证 customer_id 字段指向的记录是否存在?

$this->Order->create();
$this->Order->set('customer_id', 1);
$this->Order->set('order_date', date('Y-m-d'));
$this->Order->set('total', 100);
$this->Order->save();

是否有可应用于订单模型的 customer_id 字段的验证规则?或者,我是否必须定义自定义规则?

我想有两种解决方案: - 首先:像这样在模型中制定验证规则:

public $validate = array(
    'username' => array(
        'isUnique' => array(
            'rule' => 'isUnique',
            'message' => 'That username has already been taken',
            'on' => 'create'
        ),
        'notEmpty' => array(
            'rule' => 'notEmpty',
            'message' => 'Please enter a username'
        )
    )
);
  • 第二:如果你得到这些数据,你可以使用一些 ajax 插件来指定一些字段 directly.for 像这样的例子:http://jqueryvalidation.org/

希望对您有所帮助。

您必须创建自定义规则才能在模型验证中执行此操作。

也就是说,你想知道的很简单,所以你可以很容易地做到。

public function checkCustomerExists(){
    return $this->Customer->exists($this->data[$this->alias]['customer_id']);
}

假设您正确定义了模型关联,这将解决它。只需使用 'rule' => 'checkCustomerExists'

创建一个验证条目