Cakephp更新或添加新记录

Kei*_*wer 3 php cakephp

我有一个图片上传,将文件名添加到名为附件的表中。如果该ID已经存在,那么我希望它进行更新,如果不存在,则创建一个新记录。目前它创建了一条新记录,因此我有一个ID的多个记录。ID来自称为Addon的表。

我不确定如何在cakephp中执行此操作。

    if (!empty($this->data)) {
        $this->layout = null;
        //if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}

        // restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
        $tmp_file = $this->data['Attachment'][0]['file'];
        $tmp_file['extension'] =  array_reverse(explode('.', $tmp_file['name']));
        $tmp_file['extension'] = $tmp_file['extension'][0];
        $tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
        $this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));

        $previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id)));
        if( !empty( $previous ) ) {
            $this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
        }

        if ($this->AddOn->save($this->data, array('validate' => 'first'))) {    

            $id = $this->AddOn->Attachment->getLastInsertID();

            $att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
            $this->set('attachment',$att[0]['attachments']);

        } else {
            $tmp_file['name'] = 'INVALID FILE TYPE';
        }


        //debug($this->data);
        $this->set('file', $tmp_file);
        $this->RequestHandler->renderAs($this, 'ajax');
        $this->render('../elements/ajax');

    }
Run Code Online (Sandbox Code Playgroud)

JJJ*_*JJJ 5

save()saveAll()在设置了ID后自动更新现有行。您可以执行以下操作:

$previous = $this->AddOn->Attachment->find( /* whatever conditions you need */ );
if( !empty( $previous ) ) {
    $this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
Run Code Online (Sandbox Code Playgroud)

现在,旧记录(如果存在)将被更新。

附带说明一下,成功后的代码saveAll()没有太大意义:首先将数据保存到数据库,然后立即再次检索它。您可以继续使用$this->data已经具有相同内容的内容。

另一个注意事项:query()当您不能使用Cake的其他方法时,应仅将其作为最后的选择。query("SELECT * from attachments WHERE id = ".$id)是一个琐碎的案例,可以将其重写为$this->Model->id = $id; $this->Model->read();简单$this->Model->find()查询或使用简单查询进行重写。