laravel dropzone产品id上传问题

q35jwt9p  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(309)

假设我有一个产品,它有许多图像。我使用了dropzone js,如果我上传了图片,那么就可以了,但是如果我想用产品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 )on delete cascade on update cascade)(sql:插入到 images ( image , product_id , updated_at , created_at )值(1538483231-blog-1-3.png,1232018-10-02 12:27:11,2018-10-02 12:27:11))”

bprjcwpo

bprjcwpo1#

mysql给出“无法添加或更新子行:外键约束失败”,因为products表中没有123 id的产品。之后,您可以为它创建关系记录

vc6uscn9

vc6uscn92#

我能想到三个可能与你的问题有关的原因:
1:你可能需要在模型中填充柱。
2:因为您将它作为外键,所以必须自动设置id,而不是插入(从原点获取)或取消绑定该值。
3:这意味着u正在插入的值在原始表中不存在,因为u正在获取此错误。
祝你好运

dwthyt8l

dwthyt8l3#

如果某些列是另一个表中的外键,则不能更新该表。
如果要更新if,请首先删除包含外键的表 (images) . 在你能更新这个之后 products table。

mpgws1up

mpgws1up4#

刀片使用中

<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">

相关问题