我正在制作产品模块,其中图像将保存在不同的表格中。我能够在图像表上保存vehicle_id但无法保存图像名称。如果有的话,请给出解决方案 -
VehicleController
public function newvehicle()
{
if (empty($this->request->data)) {
}
else
{
if(!empty($this->request->data['Image']['image_path']))
{ //die('test');
$file = $this->request->data['Image']['image_path'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif', 'png'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/vehicle-images/' . $file['name']);
$this->request->data['Image']['image_path'] = $file['name'];
}
}
if ($this->Vehicle->saveAll($this->request->data))
{
$this->Session->setFlash('Vehicle Saved!');
return $this->redirect(array('action'=>'newvehicle'));
}
}
}
图片模型
App::uses('AppModel', 'Model');
class Image extends AppModel {
public $belongsTo = array(
'Vehicle' => array(
'className' => 'Vehicle',
'foreignKey' => 'image_id'
)
);
}
newvehicle.ctp
echo $this->Html->css('custom.css');
echo $this->Form->create('Vehicle', array('type' => 'file'));
echo $this->Form->input('name', array('label' => 'Na`m`e'));
echo $this->Form->input('model', array('label' => 'Model'));
echo $this->Form->input('Image.image_path', array('type' => 'file'));
$status = array('1' => 'Active', '0' => 'Inactive');
echo $this->Form->input('vehicle_state', array('options' => $status, 'default' => '1', 'label' => 'Vehicle State'));
echo $this->Form->end('Create');
车型
App::uses('AppModel', 'Model');
class Vehicle extends AppModel
{
public $hasMany = array('Image' => array
(
'className' => 'Image',
'foreignKey' => 'vehicle_id'
));
答案 0 :(得分:2)
我能看到的第一件事是,如果你想将一个值保存到另一个不是你的“主”表的表中,那么你应该使用另一个模型,尝试使用它:
if($ this-> Vehicle-> Model-> save($ this-> request-> data))
编辑 - 您的模型也未正确设置:
class Image扩展了AppModel {
public $belongsTo = array( 'Vehicle' => array( 'className' => 'Vehicle', 'foreignKey' => 'vehicle_id' ) );