我在保存和更新hasMany关联时遇到问题。似乎Cake无法以某种方式正确修补实体。
ProductGroups表:
false
ProductIdentities表:
$this->hasMany('ProductIdentities', [
'foreignKey' => 'product_group_id',
'saveStrategy' => 'replace'
]);
ProductGroupsController:
$this->belongsTo('ProductGroups', [
'foreignKey' => 'product_group_id'
]);
$这 - >请求 - >数据:
// patch entity
$productGroup = $this->ProductGroups->patchEntity($productGroup, $this->request->data, [
'associated' => [
'StaffMembers' => ['onlyIds' => true],
'ProductIdentities' => ['onlyIds' => true]
]
]);
edit.ctp
[
'group_name' => 'Creative and Performing Arts',
'active' => '1',
'product_type_id' => '2',
'staff_members' => [
'_ids' => [
(int) 0 => '103',
(int) 1 => '11',
(int) 2 => '3'
]
],
'product_identities' => [
'_ids' => [
(int) 0 => '1760',
(int) 1 => '1762',
(int) 2 => '1763',
(int) 3 => '1764'
]
]
]
如果productGroup未与任何productIdentities相关联,则可以保存。但是,如果要选择更多productIdentities或取消选择某些现有属性,则不会保存数据。相反,Cake将在product_identites表中创建新记录。
在进行调试后,我发现Cake没有正确修补实体。见下文:
<?php
echo $this->Form->input('group_name',
['class' => 'form-control']);
echo $this->Form->input('active',
['class' => 'form-control']);
echo $this->Form->input('product_type_id',
['class' => 'form-control']);
echo $this->Form->input('staff_members._ids',
['options' => $staffMembers,
'class' => 'form-control height-200']);
echo $this->Form->input('product_identities._ids',
['options' => $productIdentities,
'class' => 'form-control height-500']);
?>
onlyIds选项应该阻止Cake创建新记录,但显然它不起作用。
我已将数据格式化为Cake文档中建议的格式,所以我很困惑。
'product_identities' => [
(int) 0 => object(App\Model\Entity\ProductIdentity) {
(int) 0 => '1760',
(int) 1 => '1762',
(int) 2 => '1763',
(int) 3 => '1764',
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
(int) 0 => true,
(int) 1 => true,
(int) 2 => true,
(int) 3 => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'ProductIdentities'
}
],
http://book.cakephp.org/3.0/en/orm/saving-data.html#converting-hasmany-data
感谢任何意见/帮助。