加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

CakePHP – 在Model-> beforeSave()中从插入更改为更新

发布时间:2020-12-13 17:06:53 所属栏目:PHP教程 来源:网络整理
导读:这是我的beforeSave功能. checkExisting()检查$this-数据中的某些字段是否唯一,如果没有现有记录,则返回false,如果存在,则返回现有记录的ID.这个功能工作正常. public function beforeSave(){ if ($this-checkExisting() !== false){ $this-id = $this-check
这是我的beforeSave功能. checkExisting()检查$this->数据中的某些字段是否唯一,如果没有现有记录,则返回false,如果存在,则返回现有记录的ID.这个功能工作正常.

public function beforeSave(){
    if ($this->checkExisting() !== false){
        $this->id = $this->checkExisting();
    }
    return true;
}

我认为我的代码应该做的是:如果有现有记录,请将Model-> id设置为该现有记录的ID,因此强制CakePHP更新而不是插入.

这个代码实际上做的是插入新记录,无论如何.

如果我更改$this-> id = $this-> checkExisting(); to $this-> data [‘Model’] [‘id’] = $this-> checkExisting();,MySQL给出了一个错误(主键的重复值),因为Cake还在尝试插入,而不是而不是更新,数据.

Cake在什么阶段决定插入而不是更新? beforeSave()来不及影响这个决定吗?

编辑 – 这是我的控制器代码:

public function add(){
    if (!empty($this->data)){
        $saved = 0;
        foreach($this->data['Attendance'] as $att){
            $this->Attendance->create();
            if ($this->Attendance->save(array('Attendance'=>$att))){
                $saved++;
            }
            if ($saved > 0){
                $this->Session->setFlash('Data saved successfully','success');
            }else{
                $this->Session->setFlash('No data was saved.  Please make sure you have entered some data.','failure');
            }
        }
    }
}

考虑一下,是否与我明确调用Attendance :: create()这一事实有关?

解决方法

不,之前保存为时尚晚,无法改变这一点. Model-> save()按顺序执行以下操作:

>调用Model-> set(),传递提供的数据.这将提取一个id并设置Model-> id
>调用回调函数(包括beforeSave())
>决定是否根据Model-> id进行更新或插入

假设checkExisting()行为正确,上面的代码应该可以正常工作.我再看看你的checkExisting()代码.

另请注意,在对checkExisting()进行两次调用时,代码效率很低.这会更好:

$existing = $this->checkExisting();
if($existing) {
    $this->id = $existing;
}

编辑
我猜你已经创建了checkExisting(),因为如果其中一条记录无效,你上面的add()动作最终会保存一个部分记录集.您应该使用saveAll(),它可以在保存所有记录之前验证所有记录.

public function add() {
    if(!empty($this->data)) {
        if($this->Attendance->saveAll($this->data)) {
            $this->Session->setFlash('Data saved successfully','success');
        } else {
            $this->Session->setFlash('No data was saved.  Please make sure you have entered some data.','failure');
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读