【问题标题】:Laravel dropzone problem for upload with product_id使用 product_id 上传的 Laravel dropzone 问题
【发布时间】: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:插入imagesimageproduct_idupdated_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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

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

        3:这意味着你插入的值在原始表中不存在,因为你得到了这个错误。

        祝你好运

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-15
          • 2018-06-01
          • 2015-01-09
          • 1970-01-01
          相关资源
          最近更新 更多