2011-09-21 106 views
2

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

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

    } 

回答

4

save()saveAll()如果ID已设置自动更新现有的行。您可以执行如下操作:

$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()查询。

+0

我只是在学习cakephp。我有一个公司的代码,我努力使它正常工作。大多数应用程序都可以,但确实有很多query()。感谢这里的帮助 –

+0

数据再次被检索到的原因保存是在上传后用ajax显示在屏幕上\t \t \t $ this-> set('file',$ tmp_file); \t \t \t $ this-> RequestHandler-> renderAs($ this,'ajax'); \t \t \t $ this-> render('../ elements/ajax'); –

+0

当然,但你仍然在查询你已有的数据。 '$ this-> set('attachment',$ this-> data)'将起到相同的作用。 – JJJ