php - 使用 product_id 上传的 Laravel dropzone 问题
问题描述
假设我有一个产品,它有很多图像。我使用了 Dropzone js,如果我上传图片,那么它很好,但如果想用 product_id 存储,那么它会传递空值。没有传递任何值它的工作正常。那么我怎样才能同时存储图像名称和 product_id 呢?这是我的控制器:
public function store(Request $request)
{
if ($request->hasFile('file')){
$file= $request->file;
$fileName = $file->getClientOriginalName();
$fileName = time() .'-'.$fileName;
$productImage = public_path("uploads/products/{$fileName}"); // get previous image from folder
if (File::exists($productImage)) { // unlink or remove previous image from folder
unlink($productImage);
}
$file->move('public/uploads/products/',$fileName);
$image = new Image();
$image->image = $fileName;
$image->product_id = $request->product_id;
$image->save();
// return redirect()->route('product.index');
}
}
数据库架构:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
错误:
消息:“SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
eshop
。images
,CONSTRAINTimages_product_id_foreign
FOREIGN KEY(product_id
)REFERENCESproducts
(id
)ON DELETE CASCADE ON UPDATE CASCADE)(SQL:插入images
(image
,product_id
,updated_at
,created_at
) 值 (1538483231-blog-1-3.png, 123, 2018-10-02 12:27:11, 2018-10-02 12:27:11))"
解决方案
如果某些列是另一个表中的外键,则无法更新表。
如果要更新,首先要删除外键具有的表(images)
。之后就可以更新这个products
表了。