Laravel 雄辩地添加到 JSON

Dew*_*agg 4 mysql laravel eloquent

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

$table->json('images')->nullable();
Run Code Online (Sandbox Code Playgroud)

表称为相册。在图像中,我想存储一个包含图像名称的数组,但如何每​​次都添加到该 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();
Run Code Online (Sandbox Code Playgroud)

我需要像 Laravel 增量函数一样,但它只适用于 int 看起来像。我怎样才能做到这一点?提前致谢!

小智 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();
Run Code Online (Sandbox Code Playgroud)

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

祝你好运


小智 5

  $album = Album::where('hash', $request->album_hash)->firstOrFail();
  $arra = json_decode($album->images);
  $arra[] = $request->image->name;
  $album->update([
      'images' => $arra
  ]);
  $album->save();
Run Code Online (Sandbox Code Playgroud)

我希望对你有帮助