在Laravel中通过hasMany关系更新多个记录

时间:2020-04-21 10:47:09

标签: php laravel eloquent laravel-6 laravel-7

我正在尝试在laravel中更新多个图像,但是我无法执行此操作。当我将图像存储在数据库中时,它可以正常工作,但问题在于更新。 请让我知道我在哪里。我与图片和博客表之间有关系。

这是我的控制器代码...

public function update(Request $r, $blog)
{
    //dd($r->all());
    $type = 'blog_img';
    $chr = substr($r->title, 0, 1);

    if (!is_dir(public_path() . '/' . $type)) {
        $blogDir = public_path() . '/' . $type;
        mkdir($blogDir, 0777, true);
    }
    if (!is_dir(public_path() . '/' . $type . '/' . date("Ymd"))) {
        $dateDir = public_path() . '/' . $type . '/' . date("Ymd");
        mkdir($dateDir, 0777, true);
    }

    if (!is_dir(public_path() . '/' . $type . '/' . date("Ymd") . '/thumb')) {
        $thumbDir = public_path() . '/' . $type . '/' . date("Ymd") . '/thumb';
        mkdir($thumbDir, 0777, true);
    }

    if (!is_dir(public_path() . '/' . $type . '/' . date("Ymd") . '/small')) {
        $smallDir = public_path() . '/' . $type . '/' . date("Ymd") . '/small';
        mkdir($smallDir, 0777, true);
    }

    if (!is_dir(public_path() . '/' . $type . '/' . date("Ymd") . '/thumb' . '/' . $chr)) {
        $chrThumbDir = public_path() . '/' . $type . '/' . date("Ymd") . '/thumb' . '/' . $chr;
        mkdir($chrThumbDir, 0777, true);
    }

    if (!is_dir(public_path() . '/' . $type . '/' . date("Ymd") . '/small' . '/' . $chr)) {
        $chrSmallDir = public_path() . '/' . $type . '/' . date("Ymd") . '/small' . '/' . $chr;
        mkdir($chrSmallDir, 0777, true);
    }

    $thumbDirPath = date("Ymd") . '/thumb/' . $chr;
    $smallDirPath = date("Ymd") . '/small/' . $chr;

    if ($r->hasFile('propertyImages')) {
        $blImage = [];
        //dd($r->blog_image);
        for ($v = 0; $v < count($r->blog_image); $v++) {
            $thums = $r->blog_image;
            $filnameSmall = 'small-' . uniqid($chr) . '-' . $v . '.' . $thums[$v]->getClientOriginalExtension();
            $img = Image::make($thums[$v]->getRealPath());
            $img->resize(300, null, function ($constraint) {
                $constraint->aspectRatio();
            });
            $smallPath = public_path() . '/' . $type . '/' . date("Ymd") . '/small' . '/' . $chr . '/' . $filnameSmall;
            if (file_exists($smallPath)) {
                $this->removeImage($smallPath);
            }
            $img->save($smallPath);

            $optimizerChain = OptimizerChainFactory::create();
            $optimizerChain->optimize($smallPath);

            $filnameLarge = 'thumb-' . uniqid($chr) . '-' . $v . '.' . $thums[$v]->getClientOriginalExtension();
            $img = Image::make($thums[$v]->getRealPath());
            $img->resize(1080, null, function ($constraint) {
                $constraint->aspectRatio();
            });
            $thumbPath = public_path() . '/' . $type . '/' . date("Ymd") . '/thumb' . '/' . $chr . '/' . $filnameLarge;

            if (file_exists($thumbPath)) {
                $this->removeImage($thumbPath);
            }
            $img->save($thumbPath);
            $optimizerChain->optimize($thumbPath);

            $blImage[$v]['small'] = $filnameSmall;
            $blImage[$v]['smallDirPath'] = $smallDirPath;
            $blImage[$v]['large'] = $filnameLarge;
            $blImage[$v]['thumbDirPath'] = $thumbDirPath;
        }
    }
    else {
        $blImage = NULL;
    }

    $images = $blImage;
    $blog = Blog::find($blog);
    $blog->name = $r->bl_name;
    $blog->slug = Str::slug($r->bl_slug);
    $blog->meta_title = $r->meta_title;
    $blog->meta_desc = $r->meta_desc;
    $blog->description = $r->overview;
    $blog->status = $r->status;
    $blog->blogTag()->delete();
    $tagNames = explode(',', $r->blogtags);
    foreach ($tagNames as $key => $value) {
        $blog->blogTag()->updateOrCreate([
            'tag_name' => $value,
            'tag_slug' => Str::slug($value, '-')
        ]);
    }
    if ($images != null) {
        for ($v = 0; $v <= array_key_last($images); $v++) {
            if (!empty($images[$v])) {
                $blog->blogImage()->updateOrCreate(['id' => $images[$v]['id']], [
                    'small_thumb' => $images[$v]['small'],
                    'small_thumb_url' => $images[$v]['smallDirPath'],
                    'large_thumb' => $images[$v]['large'],
                    'large_thumb_url' => $images[$v]['thumbDirPath'],
                ]);
            }
        }
    }

    $blog->save();
    return response()->json(['status' => 1], 200);
}

这是我在查看文件中的更新图像代码:

<div class="statbox widget box box-shadow">
                                <div class="widget-header">
                                    <div class="row">
                                        <div class="col-xl-12 col-md-12 col-sm-12 col-12">
                                            <h4>Upload Blog Image</h4>
                                        </div>      
                                    </div>
                                </div>
                                <div class="widget-content widget-content-area">
                                    @forelse($blog->blogImage as $propImg)
                                    <div class="custom-file-container" data-upload-id="myFirstImage">
                                        <label>Upload (Single File) <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">x</a></label>
                                        <label class="custom-file-container__custom-file" >
                                            <input type="file" name="blog_image[]" class="custom-file-container__custom-file__custom-file-input" accept="image/*">
                                            <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
                                            <span class="custom-file-container__custom-file__custom-file-control"></span>
                                        </label>
                                        <div class="custom-file-container__image-preview"><img src="{{ asset('blog_img/'.$propImg->small_thumb_url.'/'.$propImg->small_thumb)}}" style="max-height: 90px;">
                                        </div>
                                        @empty
                                        @endforelse
                                    </div>
                                </div>
                            </div>

这是Bloh.php模型。

public function blogImage()
{
    return $this->hasMany(BlogImage::class);
}

这是BlogImage.php模型。

public function blog()
{
    return $this->hasMany(Blog::class);
}

1 个答案:

答案 0 :(得分:1)

我无法在您的控制器中找到$images[$v]['id'],但是$blImage也没有id

您有2种方法:

  1. 遍历$blog->blogImage()并按照顺序更新:

替换:

$blog = Blog::find($blog);

$blog = Blog::with('blogImage')->find($blog);

并更改关系操作的逻辑:

if (is_array($images) AND !empty($images)) {
  $blogImages = $blog->blogImage;
  $count = count($blogImages);
  for ($v = 0; $v < count($images); $v++) {
    if ($v < $count-1 AND !empty($images[$v])) {
      $blogImages[$v]->update($images[$v]);
      continue;
    }
    $blog->blogImage->create($images[$v]);
  }
}

  1. 删除或保留以前的图像,并像以前一样进行createMany

替换此:

if ($images != null) {
    for ($v = 0; $v <= array_key_last($images); $v++) {
        if (!empty($images[$v])) {
            $blog->blogImage()->updateOrCreate(['id' => $images[$v]['id']], [
                'small_thumb' => $images[$v]['small'],
                'small_thumb_url' => $images[$v]['smallDirPath'],
                'large_thumb' => $images[$v]['large'],
                'large_thumb_url' => $images[$v]['thumbDirPath'],
            ]);
        }
    }
}

对此:

if (is_array($images) AND !empty($images)) {
  // uncomment this if You want to delete previous images,
  // which is logically incorrect - since 
  // user is uploading image, not deleting it
  // $blog->blogImage()->delete(); 
  $blog->blogImage()->createMany($images);
}

manual to createMany