我通过联接表Products
将Images
映射到Products_Images
产品型号:
class Product extends AppModel {
public $hasAndBelongsToMany = array(
'Image' => array(
'className' => 'Image',
'joinTable' => 'products_images',
'dependent' => true,
'foreignKey' => 'product_id',
'associationForeignKey' => 'image_id'
)
);
}
图片模型:
class Image extends AppModel {
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'products_images',
'foreignKey' => 'image_id',
'associationForeignKey' => 'product_id'
)
);
}
产品控制器中的操作代码段:
if($this->request->is('post')) {
if(!empty($this->request->data)) {
$this->Product->create();
if($this->Product->save($this->request->data)) {
$newProductID = $this->Product->id;
foreach($this->request->data['Uploads'] as $image):
//Check if image has been uploaded
if(!empty($image['name'])) {
$ext = substr(strtolower(strrchr($image['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($image['tmp_name'], './img/uploads/products/' . $image['name']);
//prepare the Image for database entry
$this->request->data['Image']['name'] = $image['name'];
//save image
$this->Product->Image->save($this->request->data);
}
}
endforeach;
$this->Session->setFlash(
'Product has been successfully created.',
'default',
array('class' => 'alert-success')
);
return $this->redirect(array('action' => 'view',$newProductID));
} else {
$this->Session->setFlash(
'Product has could not be created. Please try again.',
'default',
array('class' => 'alert-danger')
);
return $this->redirect(array('action' => 'index'));
}
}
}
这是Products
控制器中的操作收到的内容:
ISSUE: 这很好地将Product添加到表中,它还很好地将Image添加到表中,但是它在Products_Images表中创建了4个seamingly random条目。它使image_id正确,但它会插入4个随机product_ids。