Laravel拖放区问题,用于product_id上传



>假设我有一个产品,它有很多图像。 我使用了 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(imageproduct_idupdated_atcreated_at( 值 (1538483231-blog-1-3.png, 123, 2018-10-02 12:27:11, 2018-10-02 12:27:11((">

Mysql 给出"无法添加或更新子行:外键约束失败",因为 123 id 的产品表中没有任何产品。首先,您需要创建该产品。之后,您可以为其创建关系记录

如果某些列是另一个表中的外键,则无法更新表。

如果要更新,如果首先删除外键(images)的表。之后,您可以更新此products表。

in @blade 使用

<input type="hidden" name="product_id" class="form-control m-input" value="{{$id}}">

状态

<input type="hidden" name="product_id" class="form-control m-input" value="123">

我可以想到 3 个可能与您的问题有关的原因:

1:您需要使列在模型中可填充。

2:因为您将其作为foreign_key所以您必须自动设置 id,而不是使用插入(从原点获取(或取消绑定值。

3:这意味着您要插入的值在源表中不存在,因为您收到此错误。

祝你好运

最新更新