我正在使用CakePHP 3.2和proffer插件上传图片。
我有products
和product_images
表,并使用单一表单将数据上传到两个表。
这就是我的表格
<?= $this->Form->create($product, ['type' => 'file') ?>
<?= $this->Form->input('title', ['required' => true]) ?>
<?= $this->Form->input('description', ['required' => true]) ?>
<?= $this->Form->input('product_images.0.image', ['required' => true, 'type' => 'file']) ?>
<?= $this->Form->input('product_images.1.image', ['type' => 'file']) ?>
<?= $this->Form->button('submit', ['type' => 'submit']) ?>
<?= $this->Form->end() ?>
和控制器就像
public function add()
{
$product = $this->Products->newEntity();
if ($this->request->is('post')) {
$product = $this->Products->patchEntity($product, $this->request->data, [
'associated' => ['ProductImages']
]);
if ($this->Products->save($product)) {
$this->Flash->success('Product saved');
}
}
}
但这只是将数据保存到产品表而不是产品图像。
答案 0 :(得分:0)
我了解您的模型已正确关联
<?= $this->Form->create($product, ['type' => 'file']) ?>
<?= $this->Form->input('title', ['required' => true]) ?>
<?= $this->Form->input('description', ['required' => true]) ?>
<?= $this->Form->input('product_images.0', ['required' => true, 'type' => 'file']) ?>
<?= $this->Form->input('product_images.1', ['type' => 'file']) ?>
<?= $this->Form->button('submit', ['type' => 'submit']) ?>
<?= $this->Form->end() ?>
添加名称图像以保存在数据库中
public function add()
{
$product = $this->Products->newEntity();
if ($this->request->is('post')) {
$product = $this->Products->patchEntity($product, $this->request->data);
foreach($product['product_images'] as $image) {
//Add image name who you want to save in database
$product['product_images'][]['image'] = $image['name'];
}
if ($this->Products->save($product)) {
$this->Flash->success('Product saved');
}
}
}