【发布时间】:2018-10-02 12:29:27
【问题描述】:
假设我有一个产品,它有很多图像。我使用了 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,约束images_product_id_foreign外键 (product_id) 引用products(id) 开启 删除级联开启 更新级联)(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))"
【问题讨论】:
-
您确定您的 products 表中有 123 id 的产品吗?似乎 mysql 在 products 表中没有找到任何记录,它有 123 id
-
对不起,我忘了删除静态值
标签: php mysql laravel eloquent dropzone.js