好吧,我想我的第一白水(或saveMany或saveAssociated不知道这是“正确”),其包括的hasMany关系,我似乎无法弄清楚如何蛋糕想这个数据。我可以在主表上获取名称字段来更新,但我无法获取hasMany关系来更新。CakePHP的保存数据(的hasMany关系)
我只是在正确的方向寻找一个凹凸,即时拼命学习,但想到用我的头放在墙上的洞看起来越来越诱人。
只是一个小背景我有两个表“供应商”表和“vendor_payment_types”表。在 “供应商” 表的hasMany“vendor_payment_types结构如下:
厂商表 ID,COMPANY_ID,名
vendor_payment_types ID,VENDOR_ID,类型
目前我发送到阵列控制器是(如果付款类型有一个id,这意味着它已经存在于数据库中,并且什么都不需要发生,如果没有id,需要添加它,第三部分是如果它存在于数据库中但不存在这个数组需要从dat中删除ABASE):
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
)
)
)
)
我需要发生的是一个)更新名称B)添加任何新的VendorTypes C)删除不属于POST'ed数组中,但在数据库中存在的任何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添加。在无数的“企图”上度过了美好的一天,所有这一切都没有出现。
谢谢你一百万次的任何帮助!
我正面临同样的问题。和你一样,它开始觉得我做错了什么,因为人们写了这么多预处理的东西。从[这个网站](http://mrphp.com.au/blog/working-habtm-form-data-cakephp)我得到的印象是,使用hasandbelongstomany会给我一个更原始的感觉,虽然它感觉有点不太复杂为多选。 – Ruben