使用 Laravel 批量上传和添加文件到数据库

Batch uploading and adding files to the database with Laravel

我想使用 Laravel v5.6.

通过表单添加和更新多个图像

我也在尝试将这些添加的图片与另一个模型相关联。但是在添加时,由于我在某处犯的错误,我遇到了 SQL 错误。这是错误:

SQLSTATE[HY000]: General error: 1364 Field 'imageable_id' doesn't have a default value (SQL: insert into `images` (`img_url`, `updated_at`, `created_at`) values (public/images/yxJ0BQDFz2dU5wzKk5uNreHlKl4Z5kmXDRfMug8p.png, 2020-12-19 05:43:29, 2020-12-19 05:43:29))

在此先感谢您的帮助!

我的Service.php模型文件:

use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Service extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'slug',
        'title',
        'content',
        'status',
    ];

    use HasSlug;

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }

    /**
     * Eğer `status` set ediliyorsa...
     *
     */
    public function setStatusAttribute($value)
    {
        $this->attributes['status'] = in_array($value, ['on', 'yes', 'ok', 'true']) ? 1 : 0;
    }

    /**
     * Eğer `status` alınıyorsa...
     *
     */
    public function getStatusAttribute()
    {
        return $this->attributes['status'] == 1 ? 'on' : null;
    }

    /**
     * Get all of the images for the post.
     */
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }

}

我的Image.php模型文件:


use Illuminate\Database\Eloquent\Model;

class Image extends Model
{

    /**
     * Fillable fields
     *
     */
    protected $fillable = [
        'name',
        'desc',
        'img_url',
        'imageable_id',
        'imageable_type',
    ];

    /**
     * imageable items
     *
     */
    public function imageable()
    {
        return $this->morphTo();
    }

}

ServiceController.php:

public function store(Request $request)
    {
        session()->flash('status', $request->status);

        $request->validate([
            'title' => 'required|between:5,255',
            'content' => 'required|min:10',
            // 'status' => 'accepted',
            'files.*' => 'file|image|mimes:jpeg,png|max:2048',
        ]);

        $service = new Service;
        $service->title = $request->title;
        $service->content = $request->content;
        $service->status = $request->status;
        $service->save();

        if($request->hasFile('files')) {
            collect($request->file('files'))->each(function ($file) use($service) {
                // return Storage::putFile('public/images', $file);
                // $newFile = Storage::putFile('public/images', $file);
                $newFile = $file->store('public/images');

                /**
                 *
                 * I don't know if the method of adding to the database here is correct.
                 * I'll be grateful to those who propose the truth:
                 * 
                 */
                $image = new \App\Image;
                $image->img_url = $newFile;
                // $image->imageable->create($service);
                $image->save();

                $service->images()->save($image);
            });
        }

        return redirect(route('admin.services.index'))->with('success', trans('Kayıt başarıyla eklendi'));
    }

create.blade.php:

<form action="{{ route('admin.services.store') }}" enctype="multipart/form-data" method="POST">
   @csrf
   @method('POST')

<!-- ... -->

<div class="form-group">
   <label for="files">{{ __('Yükelenecek dosya') }}:</label>
   <input type="file" name="files[]" multiple id="files" class="form-control-file" placeholder="{{ __('Yüklenecek dosyaları seçin') }}" aria-describedby="files-label">
   <small id="files-label" class="form-text text-muted">
      {{ __('Yüklenecek dosyalar .png ve .jpg türlerini içermelidir.') }}
   </small>
</div>

<!-- ... -->

</form>

当您调用 $image->save() 时,Image 还没有为 imageable_id 设置外键,并且您的数据库模式表明 imageable_id 必须有一个值。

不要调用 $image->save(),因为模型将在您调用 $service->images()->save($image) 后保存。这将设置外键并为您保存模型。因此,当它保存时,它将具有所需的带值的外键字段。