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');
}
我只是在学习cakephp。我有一个公司的代码,我努力使它正常工作。大多数应用程序都可以,但确实有很多query()。感谢这里的帮助 –
数据再次被检索到的原因保存是在上传后用ajax显示在屏幕上\t \t \t $ this-> set('file',$ tmp_file); \t \t \t $ this-> RequestHandler-> renderAs($ this,'ajax'); \t \t \t $ this-> render('../ elements/ajax'); –
当然,但你仍然在查询你已有的数据。 '$ this-> set('attachment',$ this-> data)'将起到相同的作用。 – JJJ