代码之家  ›  专栏  ›  技术社区  ›  Dewagg

Laravel雄辩地添加到JSON

  •  2
  • Dewagg  · 技术社区  · 7 年前

    首先,很抱歉我的英语不好。我有专栏:

    $table->json('images')->nullable();
    

    表被调用 相册 在里面 图像 我想用图像名称存储一个数组,但如何每次都添加到json中?我现在的代码:

    $album = Album::where('hash', $request->album_hash)->firstOrFail();
    $album->update([
        'images' => $request->image->name <= tried to do something.. My uploader everytime calls this function, so I need to get current IMAGES column value, and add new. Like ['first image name', 'second image name'], after update this must be ['first image name', 'second image name', 'third image name'] not just ['third image name']
    ]);
    $album->save();
    

    我需要做类似于laravel增量函数的事情,但它只适用于int。我该怎么做?提前感谢!

    2 回复  |  直到 7 年前
        1
  •  4
  •   Gijs Beijer    7 年前

    我认为不可能直接更改JSON,因为图像数据将以字符串形式返回。

    首先将JSON作为字符串获取,然后更新对象并更新JSON。

    比如:

    $album = Album::where('hash', $request->album_hash)->firstOrFail();
    $images = json_decode($album->images);
    
    array_push($images,  $request->image->name);
    
    $album->update(['images' => $images]);
    $album->save();
    

    注意:我没有检查此代码,但这应该会让您了解如何处理此代码

    祝你好运

        2
  •  3
  •   Ricardo Castillo    7 年前
      $album = Album::where('hash', $request->album_hash)->firstOrFail();
      $arra = json_decode($album->images);
      $arra[] = $request->image->name;
      $album->update([
          'images' => $arra
      ]);
      $album->save();
    

    我希望能帮助你