如何在CakePHP中保存具有hasMany关系的多个图像?

时间:2016-01-08 06:23:04

标签: cakephp orm cakephp-2.x

如何在辅助表中保存多个图像?

我的第一个表是Car,其中包含以下字段:

  • ID
  • 标题
  • featured_image和

我的辅助表是Gallery,其中包含以下字段:

  • ID
  • car_id
  • gallery_images

模型Car.php

class Car extends AppModel
{
    var $name='Car';
    var $hasOne = array(
        'Gallery' => array('className' => 'Gallery',
            'foreignKey' => 'car_id'
        ));
}

Model Gallery.php

class Gallery extends AppModel
{
    var $name='Gallery';
    var $belongsTo = array(
        'Car' => array('className' => 'Car',
            'foreignKey' => 'car_id',

        )
    );
}

CarController.php

$this->Car->saveAll($this->data)

1 个答案:

答案 0 :(得分:0)

要保存与汽车相关的多个图像,首先必须将您的汽车模型修改为:

class Car extends AppModel
{
    var $hasMany = array(
        'Gallery' => array(
            'className' => 'Gallery',
            'foreignKey' => 'car_id'
        ));
}

或只是

class Car extends AppModel
{
    var $hasMany = array('Gallery'); //simplified version, as fields follow convention
}

然后你必须按如下方式构建数据:

$data = array(
    'Car' => array('title' => 'Volvo'),
    'Gallery' => array(
        array('gallery_images' => '/path/image1'),
        array('gallery_images' => '/path/image1'),
        array('gallery_images' => '/path/image3'),
    ),
);

在您看来,表单应具有以下结构:

echo $this->Form->create('Car', array('action' => 'add'));
echo $this->Form->input('Car.title');
echo $this->Form->input('Gallery.0.gallery_images');
echo $this->Form->input('Gallery.1.gallery_images');
echo $this->Form->input('Gallery.2.gallery_images');
echo $this->Form->end();

CarControllers::add()中,您可以使用以下内容保存所有四条记录(一辆车和三张图片)

$this->Car->saveAll($this->request->data);

请考虑重命名字段以更好地表示您的数据。例如,gallery_images应该重命名为image_filename,并将Gallery模型化为Image的{​​{1}}。

根据Photo,它可以保存图库的外键,或者您可以将此字段移动到图库/图像表中,并将其设置为名为Car.featured_image的字段(保持'特色,正常等等'),或者也许是一个名为type的布尔值。