【问题标题】:Laravel 5.4 Multiple upload and Inserting dataLaravel 5.4 多次上传和插入数据
【发布时间】:2017-10-12 23:20:58
【问题描述】:

大家好,提前谢谢大家,首先抱歉,如果我的代码如此混乱,我还在学习^^。 我正在尝试制作具有不同属性的产品以及 3 张不同的图片(制作产品图库)和一张特色图片, 我已成功创建属性和特征图像。 问题出在我无法存储的画廊的 3 张图片上(既不在 DB 也不在图片文件夹中) 我有两个表(product 和 productgallery),它们之间的关系是 hasMany(我使用的是 Laravel 5.4)

这是我运行代码后遇到的错误

SQLSTATE[HY000]: General error: 1364 Field 'product_id' doesn't have a default value (SQL: insert into `product_galleries` (`updated_at`, `created_at`) values (2017-05-13 20:58:20, 2017-05-13 20:58:20))

(对不起我的英语,这肯定会让我更难理解我的问题)

产品控制器

 public function store(UploadRequest $request)
    {
        $product = new Product();
        $product->product_name = $request->product_name;
        $product->product_description = $request->product_description;
        if($request->hasFile('product_preview')) {
          $file = Input::file('product_preview');
          $filename = time(). '-' .$file->getClientOriginalName();
          $product->product_preview = $filename;
          $file->move(public_path().'/images/product-feature', $filename);
        }
        $product->category_id = $request->category_id;
        $product->color_id = $request->color_id;
        $product->size_id = $request->size_id;
        $product->material_id = $request->material_id;
        // $product->fantasia_id = $request->fantasia_id;
        $productgallery = new ProductGallery();
        if($request->hasFile('fileToUpload[]')) {
          $files = Input::file('fileToUpload[]');
          foreach ($request->$files as $photo) {
            $filename = time(). '-' .$photo->getClientOriginalName();
            $productgallery->product_images = $filename;
            $photo->move(public_path().'/images/product-gallery', $filename);
            $productgallery->product_id = 1;
          }
        }
        $product->save();
        $productgallery->save();
        return $this->create()->with('success', 'Uploaded Successfully');
    }

上传请求(FormRequest)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UploadRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $rules = [
          'product_name'  => 'required|max:120',
          'category_id'   => 'required|integer',
          'product_preview' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
        ];
        $fileToUpload = count($this->input('fileToUpload'));
        foreach(range(0, $fileToUpload) as $index) {
            $rules['fileToUpload.' . $index] = 'image|mimes:jpeg,bmp,png|max:2000';
        }
        return $rules;
    }
}

表单的视图

@extends('layouts.backend-master')

@section('styles')
  <link rel="stylesheet" href="">
@endsection

@section('content')

  @if (count($errors) > 0)
    <div class="alert alert-danger">
      <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
          @endforeach
        </ul>
     </div>
  @endif

  <h1>Add a new product</h1>
  <form action="{{route('products.store')}}" method="post" enctype="multipart/form-data">

    <div class="input-group">
      <label for="product_name">Name of the product</label>
      <input type="text" name="product_name" id="product_name"/>
    </div>

    <div class="input-group">
      <label for="product_description">Product Description</label>
      <textarea type="text" name="product_description" id="product_description" rows="8"></textarea>
    </div>

    <div class="input-group">
      <label for="product_preview">Feature Image:</label>
      <input type="file" name="product_preview" id="file">
    </div>

    <div class="input-group">
      <label for="category_id">Category</label>
      <select name="category_id" id="category_id">
        @foreach($categories as $category)
          <option value="{{ $category->id }}">{{ $category->category_name }}</option>
        @endforeach
      </select>
    </div>

    <div class="input-group">
      <label for="color_id">Color</label>
      <select name="color_id" id="color_id">
        @foreach($colors as $color)
          <option value="{{ $color->id }}">{{ $color->color_name }}</option>
        @endforeach
      </select>
    </div>

    <div class="input-group">
      <label for="size_id">Size</label>
      <select name="size_id" id="size_id">
        @foreach($sizes as $size)
          <option value="{{ $size->id }}">{{ $size->size_name }}</option>
        @endforeach
      </select>
    </div>

    <div class="input-group">
      <label for="material_id">Material</label>
      <select name="material_id" id="material_id">
        @foreach($materials as $material)
          <option value="{{ $material->id }}">{{ $material->material_type }}</option>
        @endforeach
      </select>
    </div>

    <div class="input-group">
      <label for="fileToUpload">Product Gallery:</label>
      <input type="file" name="fileToUpload[]" id="fileToUpload" multiple >
    </div>

    <button type="submit" class="btn">Add</button>
    <input type="hidden" name="_token" value="{{Session::token()}}">
  </form>
@endsection

@section('scripts')
@endsection

谢谢

【问题讨论】:

  • 您在上面得到的错误是说您正在尝试插入一个以 product_id 作为字段但您没有插入的数据库表,因此有一个默认值。所以它会导致错误。要么将该字段更改为具有默认值(假设为 0 ),要么您始终希望确保它具有您需要确保在插入时包含一个值的值。那是你的主身份证吗?如果是这样,您是否忘记让它自动递增?
  • 我希望 product_id 自动填充产品表的 ID @scott
  • 基本上我想知道如何有一个表单将数据提交到适当的表并将产品表的ID分配给产品库表@Scott中的product_id(外键)

标签: laravel laravel-5.4


【解决方案1】:

您需要查看 Laravel 关系 API 文档。这是一个阅读更多相关信息的链接Laravel 5.4 Eloquent Relationships


解决该问题的快速提示

您应该在您的数据库/迁移文件中添加一个外键
对于迁移,您可以简单地添加

$table->foreign('product_id')->references('id')->on('products');

并将此方法添加到您的产品模型

public function productgallery(){
 return $this->hasMany(Productgallery::class);
}

这是您的 Productgallery 模型

public function product(){
 return $this->belongsTo(Product::class);
}

注意:您仍然需要在请求中填充 product_id 字段


包解决方案

我建议您为此使用 3rd 方包,因为它的工作量更少、更清洁且使用起来更稳固。 您可以查看更多spatie's medialibrary for Laravel

【讨论】:

  • 谢谢你的回答,我都做了,我不能做的是如何填充product_id@Rezrazi,我试过这个$productgallery-&gt;products()-&gt;associate($product);$productgallery-&gt;product_id = $request-&gt;id;但没有运气
  • 您可以使用attach 或者只是在您的请求中添加$productgallery-&gt;product_id = $product-&gt;id 我建议您对您的模型使用create 方法,不推荐使用new
【解决方案2】:

我想这就是你想要的。

这将创建一个新的Product 并为$request-&gt;file('fileToUpload[]') 中传递的每个图像创建一个新的ProductGallery

$product = new Product();
$product->product_name = $request->product_name;
$product->product_description = $request->product_description;
if($request->hasFile('product_preview')) {
  $file = Input::file('product_preview');
  $filename = time(). '-' .$file->getClientOriginalName();
  $product->product_preview = $filename;
  $file->move(public_path().'/images/product-feature', $filename);
}
$product->category_id = $request->category_id;
$product->color_id = $request->color_id;
$product->size_id = $request->size_id;
$product->material_id = $request->material_id;
// $product->fantasia_id = $request->fantasia_id;


// First save the product (so that you have it's ID)
$product->save();
// Then create galleries
if($request->hasFile('fileToUpload[]')) {
  $files = Input::file('fileToUpload[]');
  foreach ($files as $photo) {
    $productgallery = new ProductGallery();
    $filename = time(). '-' .$photo->getClientOriginalName();
    $productgallery->product_images = $filename;
    $photo->move(public_path().'/images/product-gallery', $filename);
    $productgallery->product_id = $product->id; // Save it to the newly created product
    $productgallery->save();
  }
}
return $this->create()->with('success', 'Uploaded Successfully');

【讨论】:

  • 感谢开发,但我更新了代码但仍然无法正常工作。 @dev,你认为我的验证可以吗?
  • 它执行保存新产品的代码的第一部分,但它根本没有进入第二部分,因此它没有画廊,我还在代码中添加了$productgallery = new ProductGallery();,但没有运气@开发
  • 发生这种情况是因为您没有在 Input::file('filesToUpload[]') 数组中发送任何文件。为什么我不知道。但我认为你的后端代码应该像这样工作。
猜你喜欢
  • 2017-08-29
  • 2017-09-24
  • 2015-05-24
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 2018-02-04
  • 2017-07-27
  • 1970-01-01
相关资源
最近更新 更多