別テーブルで画像を管理、例えばuserとimagesテーブルで分けたい場合。
まずはimagesテーブルを作る。
CREATE table images (
`id` int(10) unsigned NOT NULL auto_increment,
`model` varchar(20) NOT NULL,
`user_id` int(11) NOT NULL,
`name` varchar(32) NOT NULL,
`image` varchar(255) NOT NULL,
`dir` varchar(255) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`size` int(11) DEFAULT 0,
`active` tinyint(1) DEFAULT 1,
PRIMARY KEY (`id`)
);
Image でactsAsを宣言。belongsToでユーザとのリレーションを構築。
imagesテーブルのuser_idで紐付けたいので、foreingkeyはuser_idで。
画像格納パスは画像ID毎になる。(webroot/files/thumb/image_id/xxxx.jpgのようなかんじ)
‘pathMethod’をflatにすれば、全ての画像は’path’のディレクトリ配下に一括格納。
public $actsAs = array(
'Upload.Upload' => array(
'image' => array(
'path' => '{ROOT}webroot{DS}files{DS}thumb{DS}',
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'thumb' => '80x80'
)
)
)
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
),
);
User モデルではhasManyでimageを。
public $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'user_id',
'conditions' => array(
'Image.model' => 'User',
),
)
);
同じくUserモデル内で画像登録用の関数を用意。
public function createWithImages($data) {
// Sanitize your images before adding them
$images = array();
if (!empty($data['Image'][0])) {
foreach ($data['Image'] as $i => $image) {
if (is_array($data['Image'][$i])) {
// Force setting the `model` field to this model
$image['model'] = 'User';
// Unset the foreign_key if the user tries to specify it
if (isset($image['foreign_key'])) {
unset($image['foreign_key']);
}
$images[] = $image;
}
}
}
$data['Image'] = $images;
// Try to save the data using Model::saveAll()
$this->create();
if ($this->saveAll($data)) {
return true;
}
// Throw an exception for the controller
throw new Exception(__("This post could not be saved. Please try again"));
}
そしてuserContollerでaddするときに、上の関数を使う。
.....
if ($this->User->save($this->request->data)) {
// add for image upload
$this->User->createWithImag,es($this->request->data);
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
....
viewはこのように、モデルをhiddenで持たせておく。
echo $this->Form->input('Image.0.image', array('type' => 'file', 'label' => 'Image'));
echo $this->Form->input('Image.0.model', array('type' => 'hidden', 'value' => 'User'));
複数登録させたいときは、Image.0.imageを増やしていけば良さそうだ。