如果我的数据库中存在ID,我想更新记录。如果ID不存在则创建记录。这是我的Controller添加功能中的代码
public function add () {
$googleCategory = $this->request->data;
foreach ($googleCategory as $key => $value) {
if(empty($value['category'])){
unset($value);
}
$this->AccountShopMeta->create();
$data['shop_id'] = $value['shop_id'];
$data['name'] = $value['category'];
$data['value'] = $value['url_key'];
$data['tag'] = '';
if($this->AccountShopMeta->save($data)){
$account_shop_meta = $this->AccountShopMeta->read();
$this->set($account_shop_meta);
$this->set('_serialize', array_keys($account_shop_meta));
}
}
}
答案 0 :(得分:1)
如果我明白你的要求可能会对你有帮助。不要使用Create。如果id存在于给定数组中,则将自动对该ID进行更新。否则将创建新行。
public function add () {
$googleCategory = $this->request->data;
foreach ($googleCategory as $key => $value) {
if(empty($value['category'])){
unset($value);
}
if(!empty($value[id])){
$data['id']=$value[id];
}
$data['shop_id'] = $value['shop_id'];
$data['name'] = $value['category'];
$data['value'] = $value['url_key'];
$data['tag'] = '';
if($this->AccountShopMeta->save($data)){
$account_shop_meta = $this->AccountShopMeta->read();
$this->set($account_shop_meta);
$this->set('_serialize', array_keys($account_shop_meta));
}
}
}
答案 1 :(得分:0)
我想如果id不存在,它就会变为空,在这种情况下,在foreach中添加以下条件,至少在上面保存动作:
foreach ($googleCategory as $key => $value) {
if(isset($value['id']) && !empty($value['id'])){
$this->AccountShopMeta->id = $value['id'];
// your remaining code within loop here
//
}
}
如果存在,请不要忘记为您的视图(表单)发送id的数据..