在CakePHP中使用saveAssociated方法

时间:2012-04-19 14:19:29

标签: php cakephp cakephp-2.1 cakephp-appmodel

我试图在saveAssociated中使用CakePHP方法但没有取得很大成功,该方法似乎部分有效,事实上我在保存过程中有三个模型: Character$hasMany> PropertyLabel所以这是Character模型:

class Character extends AppModel {
    public $name = 'Character';
    public $belongsTo = 'User';
    public $hasMany = array (
        'Property' => array (
            'dependent' => true
        )
    );
    public $hasOne = array (
        'Label' => array (
            'dependent' => true
        )
    );
    public $validate = array (
        'name' => array (
            'required' => true,
            'rule' => array('between', 0, 100),
            'message' => 'This is the error message for "name" field'
        ),
        'description' => array (
            'allowEmpty' => true,
            'rule' => array('between', 0, 100),
            'message' => 'This is the error message for "description" field'
        )
    );
}

这是我从表单中获得的数据:

array(
    'Character' => array(
        'name' => 'Character name',
        'description' => 'Character description',
        'image' => 'http://url.com/image.jpg'
    ),
    'Label' => array(
        'name' => 'Basic attributes',
        'value' => 'Value'
    ),
    'Property' => array(
        (int) 0 => array(
            'name' => 'Strenght',
            'value' => '15'
        )
    )
)

然后在我的CharactersController我这样做saveAssociated数据:

class CharactersController extends AppController {

    public $uses = array ('Character', 'Property', 'Label');

    public function add () {
        if (!empty($this->request->data)) {
            $this->Character->saveAssociated($this->request->data);
        }
        debug ($this->request->data);
    }

}

Character数据已成功保存,但未LabelProperty,我错了?

2 个答案:

答案 0 :(得分:1)

您是否在其他两个模型中声明了模型关联的另一端?好好看看this page。如果使用$hasAndBelongsToMany关联,可能会让生活更轻松。

答案 1 :(得分:0)

尝试使用saveAll方法而不是saveAssociated。