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

Php 通过Laravel中的hasMany关系更新多个记录,php,laravel,eloquent,laravel-6,laravel-7,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

我正在尝试更新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);
}
下面是BlogImage.php模型

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

我无法在您的控制器中找到您如何获得
$images[$v]['id']
,显然,自从
$blImage
以来,任何地方都没有
id

你有两种方法:

  • 循环浏览
    $blog->blogImage()
    ,并按顺序更新:
  • 替换:

    $blog=blog::find($blog)

    $blog=blog::with('blogImage')->查找($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]);
      }
    }
    
    为此:

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

    您必须更改关系方法我无法在您的控制器中找到您如何获得
    $images[$v]['id']
    id
    BlogImage
    model primaryid@sainitor:)我知道它是主id,但当您创建图像数组时,并没有定义
    ['id']
    字段到it@sainitor我认为最好按照下面我的答案中的第二种方式来做。
    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);
    }