使用Laravel将JSON转换为MySQL列中的数组

时间:2021-08-12 21:16:00

I have a column that stores a data in JSON format in MySQL table in form of

我有一个列,以MySQL的形式存储JSON格式的数据

a:3:{s:2:"12";s:0:"";s:2:"34";s:0:"";s:2:"56";s:10:"1234567890";}

But since $cast was introduced in Laravel 5, I was planing to reformat my data and code to use with array casting.

但是由于在Laravel 5中引入了$ cast,我计划重新格式化我的数据和代码以用于数组转换。

Didn't find a direct conversion tips, so tried this:

没有找到直接的转换提示,所以尝试了这个:

  1. Created a column with same attributes (colB) as in the original column (colA).
  2. 创建了与原始列(colA)中具有相同属性(colB)的列。
  3. Inserted this in my model protected $casts = ['colA' => 'json', 'colB' => 'array'];
  4. 在我的模型中插入了这个受保护的$ casts = ['colA'=>'json','colB'=>'array'];
  5. Executed this code:
  6. 执行此代码:

foreach(Model::all() as $item){
   $item->colB = $item->colA;
   $item->save();
}

Code executed w/o errors, but nothing happened. colB was empty. Than I though maybe Laravel doesn't like my JSON formatting, so I change the code to this:

代码执行没有错误,但没有任何反应。 colB是空的。比起我可能Laravel不喜欢我的JSON格式,所以我将代码更改为:

foreach(Model::all() as $item){
   $item->colB = unserialize($item->colA);
   $item->save();
}

And protected $casts = ['colB' => 'array'];

并且受保护的$ casts = ['colB'=>'array'];

But I got unserialize() expects parameter 1 to be string error, even though if I dd($item->colA) I get a perfect string. And, which is more amazing, if I dd(unserialize($item->colA)) I get a perfect array.

但我得到unserialize()期望参数1是字符串错误,即使我dd($ item-> colA)我得到一个完美的字符串。而且,这更令人惊讶,如果我dd(反序列化($ item-> colA))我得到一个完美的数组。

I though maybe my data is causing this, and tried doing that with a table which had a single row to no avail.

我可能也许我的数据导致了这种情况,并尝试使用一个单行无效的表格。

Any tips appreciated!

任何提示赞赏!

1 个解决方案

#1


0  

If you are using $fillable and $guarded, make sure colB has been added to $fillable so you can update it.

如果您使用$ fillable和$ guarded,请确保colB已添加到$ fillable,以便您可以更新它。

E.g.

例如。

protected $fillable = [ 'colA', 'colB' ];

Could be the reason why your first script didn't change anything in the database...

可能是你的第一个脚本没有改变数据库中任何东西的原因......

The other option is to unguard everything in your model...

另一个选择是让你的模型中的所有东西都无法防范......

protected $guarded = [];

#1


0  

If you are using $fillable and $guarded, make sure colB has been added to $fillable so you can update it.

如果您使用$ fillable和$ guarded,请确保colB已添加到$ fillable,以便您可以更新它。

E.g.

例如。

protected $fillable = [ 'colA', 'colB' ];

Could be the reason why your first script didn't change anything in the database...

可能是你的第一个脚本没有改变数据库中任何东西的原因......

The other option is to unguard everything in your model...

另一个选择是让你的模型中的所有东西都无法防范......

protected $guarded = [];