簡體   English   中英

使用Laravel批量上傳和添加文件到數據庫

[英]Batch uploading and adding files to the database with Laravel

我想使用 Laravel v5.6 在表單上添加和更新多個圖像。

我還試圖將這些添加的圖片與另一個 model 相關聯。 但是在添加時,由於我在某處犯了錯誤,我遇到了 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 model 文件:

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 model 文件:


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'));
    }

創建.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() ,因為 Model 將在您調用$service->images()->save($image)后保存。 這將設置外鍵並為您保存 model。 因此,當它保存時,它將具有所需的外鍵字段和值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM