我在尝试保存包含 4 张图片的文章时遇到一些问题。问题是我需要使用文章 id 来命名图片,例如article_id."-"$i
由于我每篇文章只有 4 张图片,因此$i应该是 1 到 4 或 0 到 3。
现在的问题是,为了实现这一点,我需要创建并保存文章模型,以便我可以有一个 id 来使用,但是在执行所有脚本以制作拇指并形成名称之后,当我去 Article->saveAssociated() 时,我创建了两倍的文章记录!! 我试图在保存之前将 id 设置为 "-1",但什么都没有......
任何建议将不胜感激!!
法典:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}
而不是
$this->Article->saveAssociated();
这将再次保存文章,只需使用如下内容单独保存图像:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
另一种选择(不一定更好 - 只是另一种选择)只是将新创建的文章id
附加到现有的Article
数组中,然后saveAssociated()
。 如果文章的数据中有id
,它将更新而不是创建。 我会建议上面的第一个答案,但是 - 只是集思广益其他选项,以防这对某人的情况有所帮助:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images