CakePHP深(多个相关模型)验证?

时间:2015-06-08 19:29:06

标签: associations cakephp-2.3

我有一个模型结构:

Organization belongsTo Address belongsTo CountryCode

因此,Organization有外键:mailing_address_idphysical_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!');

在这种情况下,我收到CountryCodenull的错误。

为什么CountryCode无法验证或加载?

验证应该在两步之后工作吗?

1 个答案:

答案 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));
}