Cakephp更新或添加新记录

时间:2011-09-21 19:28:07

标签: php cakephp

我有一个图片上传,它将文件名添加到名为附件的表中。如果id已经存在,那么我希望它更新,如果没有,则创建一个新记录。目前它创建了一个新记录,所以我有一个id的多个记录。 id来自一个名为Addon's的表。

我不确定如何在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');

    }

1 个答案:

答案 0 :(得分:4)

如果已设置ID,则

save()saveAll()会自动更新现有行。你可以这样做:

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

现在旧记录会更新(如果存在)。

作为旁注,成功saveAll()之后的代码没有多大意义:首先,您要将数据保存到数据库,然后立即再次检索它。您可以继续使用已经具有相同内容的$this->data

另一方面注意:当你不能使用Cake的其他方法时,你应该只使用query()作为最后的手段。 query("SELECT * from attachments WHERE id = ".$id)是一个简单的案例,可以重写为$this->Model->id = $id; $this->Model->read();或使用简单的$this->Model->find()查询。