我试图在saveAssociated
中使用CakePHP
方法但没有取得很大成功,该方法似乎部分有效,事实上我在保存过程中有三个模型:
Character
,$hasMany
> Property
和Label
所以这是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
数据已成功保存,但未Label
和Property
,我错了?
答案 0 :(得分:1)
您是否在其他两个模型中声明了模型关联的另一端?好好看看this page。如果使用$hasAndBelongsToMany
关联,可能会让生活更轻松。
答案 1 :(得分:0)
尝试使用saveAll方法而不是saveAssociated。