0

控制器:

    $data =
            array(
                'ContentI18n' =>
                array(
                    0 =>
                    array(
                        'title' => 'first',
                        'author' => 'first',
                        'source' => 'sgfsdfrst',
                        'lang' => 'fa',
                    ),
                ),
                'Content' =>
                array(
                    'publish' => 1,
                    'type' => 3,
                    'pages' => 8,
                    'volume' => 7,
                    'modified' => '2012-05-27 14:16:37',
                    'created' => '2012-05-27 14:16:37',
                    'lang' => 'fa',
                ),
    );
$this->Content->create();
$this->Content->saveAll($data);

模型:

public $hasMany = array(
    'ContentI18n' => array(
        'className' => 'ContentI18n',
    )
);

行为中的 beforeSave 函数:

public function beforeSave(Model $model) {
    // Define the new Translate model
    App::uses($model->name . 'I18n', 'Model');
    $varI18n = $model->name . 'I18n';
    $modelI18n = new $varI18n;


    foreach ($model->data[$model->name] as $key => $data) {
        if (!in_array($key, $this->setting))
            $modelData[$model->name][$key] = $data;
        else
            $modelData[$model->name . 'I18n'][0][$key] = $data;
    }
    $modelData[$model->name . 'I18n'][0]['lang'] = $model->locale;
    $modelData[$model->name]['lang'] = $model->locale;
    $model->data = $modelData;

    //pr($model->data);
    return TRUE;
}

每件事似乎都是因为当直接保存它时,它是用saveAll. 但是当我在行为中使用相同的数据结构时没有任何错误。

4

1 回答 1

2

我发现 beforeSave 回调不会被 saveAll 触发。为了在 saveAll 之前执行一些代码,我们必须覆盖模型中的 saveAll 函数。

public function saveAll($data, $options = array()) {
            /*
            your code you want execute before saving...
            */
    parent::saveAll($data, $options);
}

对于其他保存方法,例如 saveMany、saveAssociated、... beforeSave 由它们触发。

于 2012-08-20T10:00:30.963 回答