好吧,我正在尝试包含 hasMany 关系的第一个 saveAll (或 saveMany 或 saveAssociated 不确定哪个是“正确的”),我似乎无法弄清楚 cake 需要这些数据。我可以更新主表上的名称字段,但无法更新 hasMany 关系。
我只是在寻找正确的方向,我渴望学习,但是用我的头在墙上挖一个洞的想法看起来越来越诱人。
只是一点背景我有两个表一个“供应商”表和一个“vendor_payment_types”表。“vendors”表有很多“vendor_payment_types”。结构如下:
供应商表 ID、公司 ID、名称
vendor_payment_types id、vendor_id、类型
目前我发送给控制器的数组是(如果支付类型有一个 id,这意味着它已经存在于数据库中并且不需要发生任何事情,如果没有 id 它需要添加,第三部分是如果它存在于数据库中但不在此数组中,需要从数据库中删除):
Array
(
[0] => Array
(
[Vendor] => Array
(
[id] => 7
[company_id] => 2
[name] => Test Vendor
[VendorPaymentTypes] => Array
(
[0] => Array
(
[vendor_id] => 7
[id] => 13
[type] => payable
)
[1] => Array
(
[vendor_id] => 7
[type] => check
)
[2] => Array
(
[vendor_id] => 7
[id] => 14
[type] => cash
)
)
)
)
我需要做的是 a) 更新名称 b) 添加任何新的 VendorTypes c) 删除任何不在 POST 数组中但存在于数据库中的 VendorTypes。以下是我在 VendorController 中的内容:
public function save() {
$vendors = array();
$companyid = $this->Auth->user('company_id');
$needle = 'new';
$i = 0;
// Setup array and also if id of payment_type includes "new" unset the id so cake will add a new and not try and match id and update
if ($this->request->is('post')) {
foreach ($this->request->data['Vendor'] as $vendorId => $vendor) {
$vendors[$vendorId]['Vendor']['id'] = $vendorId;
$vendors[$vendorId]['Vendor']['company_id'] = $companyid;
$vendors[$vendorId]['Vendor']['name'] = $vendor['name'];
foreach ($vendor['VendorTypes'] as $type => $val) {
if ($val != '0') {
$vendors[$vendorId]['Vendor']['VendorPaymentTypes'][$i]['vendor_id'] = $vendorId;
$vendors[$vendorId]['Vendor']['VendorPaymentTypes'][$i]['id'] = $val;
$vendors[$vendorId]['Vendor']['VendorPaymentTypes'][$i]['type'] = $type;
if (strstr($vendors[$vendorId]['Vendor']['VendorPaymentTypes'][$i]['id'], $needle)) {
unset($vendors[$vendorId]['Vendor']['VendorPaymentTypes'][$i]['id']);
}
$i++;
}
}
}
// Clean up array to make it an array starting at 0 and not based on vendor['id']
$cleanedarr = array();
foreach ($vendors as $vendor => $data) {
$cleanedarr[] = $data;
}
// Currently this only updates the name
if ($this->Vendor->saveAll($cleanedarr, array('deep' => TRUE) )) {
$this->Session->setFlash('Updated Vendors!');
die(pr($this->Vendor->getDataSource()->getLog()));
} else {
$this->Session->setFlash('Failed to Update');
}
}
}
供应商模型设置为
public $name = 'Vendor';
public $hasMany = array(
'VendorPaymentTypes' => array(
'className' => 'VendorPaymentTypes',
'foreignKey' => 'vendor_id',
'dependent' => true
)
);
我什至还没有开始处理删除部分,因为我无法添加新的 vendor_types。在无数次“尝试”上度过了美好的一天,但都一无所获。
感谢您一百万次的帮助!