2016-01-08 92 views
0

如何在輔助表格中保存多個圖像?如何在CakePHP中使用hasMany關係保存多個圖像?

我的第一表是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' 
     )); 
} 

型號Gallery.php

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

     ) 
    ); 
} 

汽車Controller.php這樣

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

請說明什麼是字段'gallery_images'和它包含的數據類型。您打算如何存儲圖像的文件名? –

+0

gallery_images是圖庫表的字段名稱,其中包含圖像名稱和數據類型是varchar和我的計劃 – jay

回答

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_filenameGalleryImagePhoto

按照Car.featured_image,它可以爲圖庫保存一個外鍵,或者您可以將該字段移動到圖庫/圖像表並使其成爲名爲type(保持'精選,正常等')的字段,或者一個名爲is_featured的布爾值。

相關問題