我有一个模型结构:
Organization
belongsTo Address
belongsTo CountryCode
因此,Organization
有外键:mailing_address_id
和physical_address_id
Address
有外键:country_code_id
在Organization
模型中,关系定义为:
public $belongsTo = array(
'MailingAddress' => array('className'=>'Address', 'foreignKey'=>'mailing_address_id')
, 'PhysicalAddress' => array('className'=>'Address', 'foreignKey'=>'physical_address_id')
);
这看起来效果很好 - 验证功能正常等等。
在Address
模型中,关系定义为:
public $belongsTo = array(
'CountryCode' => array('className'=>'CountryCode', 'foreignKey'=>'country_code_id')
);
在我的OrganizationsController
中,在创建新组织的功能中,我使用此代码测试验证:
if($this->Organization->saveAll(
$data, array('validate'=>'only')
)) {
// Validates
$this->DBG('Org validated.');
} else {
// does not validate
$this->DBG('Org NOT NOT NOT validated.'.print_r($this->Organization->invalidFields(),true));
}
$data
数组看起来像验证。
2015-06-08 21:03:38 Debug: Array
(
[Organization] => Array
(
[name] => Test Organization
)
[MailingAddress] => Array
(
[line1] => 100 Main Street
[line2] =>
[city] => Houston
[state] => TX
[postal_code] => 77002
[CountryCode] => Array
(
[name] => United St
)
)
[PhysicalAddress] => Array
(
[line1] => 100 Main Street
[line2] =>
[city] => Houston
[state] => TX
[postal_code] => 77002
[CountryCode] => Array
(
[name] => United St
)
)
)
国家/地区代码不应该使用我在CountryCode
模型中设置的规则进行验证:
public $validate = array(
'name' => array(
'nonemptyRule' => array(
'rule' => 'notEmpty'
,'required' => 'create'
,'message' => 'Must be provided.'
)
,'dupeRule' => array(
'rule' => array('isUnique', array('name','code'), false)
,'message' => 'Duplicate'
)
)
,'code' => array(
'rule' => 'notEmpty'
,'required' => 'create'
,'message' => 'Must be provided.'
)
);
但是,验证Organization->saveAll
上的PASSES。
另外,如果我尝试从CountryCode
访问OrganizationController
模型,则表示未加载。
如:
$this->Organization->MailingAddress->CountryCode->invalidate('name','Invalid!');
在这种情况下,我收到CountryCode
为null
的错误。
为什么CountryCode无法验证或加载?
验证应该在两步之后工作吗?
答案 0 :(得分:0)
事实证明,在验证(和保存)时有一个深选项。这里记录了saveAll选项:
http://book.cakephp.org/2.0/en/models/saving-your-data.html
因此,如果您包含深选项,问题中的验证功能将非常有效:
if($this->Organization->saveAll(
$data, array('validate'=>'only', 'deep'=>true)
)) {
// Validates
$this->DBG('Org validated.');
} else {
// does not validate
$this->DBG('Org NOT NOT NOT validated.'.print_r($this->Organization->invalidFields(),true));
}