Laravel雄辩地添加到JSON

时间:2018-04-10 14:53:53

标签: mysql laravel eloquent

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

$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 个答案:

答案 0 :(得分:1)

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

首先将JSON作为字符串获取,然后更新Object并更新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();

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

祝你好运

答案 1 :(得分:0)

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

我希望能帮到你