我有两个模型,即Product和ProductSpecification,它们具有以下关系:
folder2
和
(Product Model)
public $hasMany = array(
'ProductSpecification' => array(
'className' => 'ProductSpecification',
'foreignKey' => 'product_id',
'dependent' => true
)
);
使用CakePHP表单助手我发布了ProductSpecification数据,然后我使用(ProductSpecification Model)
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id'
)
);
方法(或saveAll
,我已尝试过两者)来保存数据。 POST后,saveAssociated
给出了以下输出:
debug($this->request->data)
这很好,对..?现在,调试后的行我使用以下代码保存(我也尝试过saveAssociated):
array(
'Product' => array(
'id' => '2'
),
'ProductSpecification' => array(
'title' => 'test',
'step' => '1',
'position' => '1'
)
)
由于某些奇怪的原因,这会在我的ProductSpecification表中保存三(!)个空行,只设置if($this->Product->saveAll($this->request->data))
字段(和product_id
);字段id
,title
和step
为空。当我运行position
时,会发生完全相同的行为。我做错了什么?
我正在运行CakePHP 2.x。
答案 0 :(得分:2)
您的保存数据应该更像这样: -
array(
'Product' => array(
'id' => '2'
),
'ProductSpecification' => array(
array(
'title' => 'test',
'step' => '1',
'position' => '1'
)
)
);
ProductSpecification
的值需要作为hasMany
关系的数字索引数组传递。
此外,请确保在传递关联数据时使用saveAssociated()
而不是saveAll()
,因此无需使用包装器方法(应尽可能避免使用)。