我正在使用上传插件 2.0 josegonzalez。Cakephp 的图像上传器,效果非常好。
但是我遇到了一个问题,我可以使用createWithAttachments
插件的一部分。
一切都很好,除了一件事。我不想在上传新附件(照片)时创建新项目(ID、名称等)。
一个项目有更多的附件(照片),用户可以为每个项目上传总共 10 张照片。
来自Project.php
(模型)的代码
<?php
class Project extends AppModel {
/* the rest of your model here */
public function createWithAttachments($data) {
// Sanitize your images before adding them
$images = array();
if (!empty($data['Image'][0])) {
foreach ($data['Image'] as $i => $image) {
if (is_array($data['Image'][$i])) {
// Force setting the `model` field to this model
$image['model'] = 'Project';
$images[] = $image;
}
}
}
$data['Image'] = $images;
// Try to save the data using Model::saveAll()
$this->create();
if ($this->saveAll($data)) {
return true;
}
// Throw an exception for the controller
throw new Exception(__("This post could not be saved. Please try again"));
}
}
?>
来自ProjectsController.php
(控制器)的代码
<?php
class ProjectsController extends AppController {
/* the rest of your controller here */
public function cms_album() {
if ($this->request->is('post')) {
try {
$this->Project->createWithAttachments($this->request->data);
$this->Session->setFlash(__('The message has been saved'));
} catch (Exception $e) {
$this->Session->setFlash($e->getMessage());
}
}
}
}
?>
每次我向数据库表中添加 10 张照片时,它都会在数据库表attachments
中创建一个新项目projects
。我只希望附件是新的,并保存我从表单部分获得的项目的 IDecho $this->Form->input('Image.'.$i.'.foreign_key', array('type' => 'hidden', 'value' => ''.$this->params->pass[0].''));
我希望我清楚地写出了我的问题,并且有人可以帮助我。我尝试了很多事情,甚至试图用一个AttachmentsController
(没有运气)来完成
更新:(在Anil kumar的 awnser 之后)
这是一个print_r
在$data
它使用之前if($this->saveAll($data))
Array
(
[Image] => Array
(
[0] => Array
(
[model] => Project
[foreign_key] => 7
[attachment] => Array
(
[name] => DSCN4923.JPG
[type] => image/jpeg
[tmp_name] => /tmp/phpGbIKTl
[error] => 0
[size] => 141994
)
)
[1] => Array
(
[model] => Project
[foreign_key] => 7
[attachment] => Array
(
[name] => DSCN4921.JPG
[type] => image/jpeg
[tmp_name] => /tmp/phpJBeYxk
[error] => 0
[size] => 216931
)
)
[2] => Array
(
[model] => Project
[foreign_key] => 7
[attachment] => Array
(
[name] => DSCN3810.JPG
[type] => image/jpeg
[tmp_name] => /tmp/phpR6sflk
[error] => 0
[size] => 1304426
)
)
)
)