我正在使用上传插件 2.0 josegonzalez。 Cakephp 的图像 uploader 效果非常棒。
但是我遇到了问题,我可以使用插件的 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
( Controller )的代码
<?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
中创建一个新项目。我只希望附件是新的,并保存从表单部分获取的项目 ID echo $this->Form->input('Image.'.$i.'.foreign_key', array( 'type' => '隐藏', 'value' => ''.$this->params->pass[0].''));
我希望我清楚地写出了我的问题,并且有人可以帮助我。我尝试了很多事情,甚至尝试使用 AttachmentsController
来完成(没有运气)
更新:(在Anil kumar的芒瑟之后)
这是在使用 if($this->saveAll($data)) 之前
$data
上的 print_r
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
)
)
)
)
最佳答案
删除项目模型中的$this->create();
,
并确保$data
不包含与项目相关的任何数据$this->saveAll($data);
The "saveAll" function is just a wrapper around the "saveMany" and "saveAssociated" methods.
因此它将保存模型数据以及关联的模型数据,
最好使用 $this->Image->saveMany($data)
而不是
$this->saveAll($data)
更多信息请查看saveAll .
更新
只需注释这些行即可。
// $this->create();
// if ($this->saveAll($data)) {
// return true;
// }
并将上面的内容替换为
if ($this->Image->saveMany($data)) {
return true;
}
关于Cakephp:添加新附件而不添加新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19798211/