php - Laravel 转换数组仍然返回一个字符串

标签 php laravel laravel-5

当检索列时,我想将其作为数组获取,但它作为字符串返回。

迁移

$table->text('balance')->nullable();

在模型上(根据 Laravel 文档)

protected $casts = [
   'balance' => 'array',
];

将数据保存到余额栏时

$exchange = Exchange::findOrFail($id);
$exchange->balance = json_encode($balance);
$exchange->save();

检索模型时

$exchanges = Exchange::orderBy('title')->get();

在 View 中

foreach($exchanges as $ex)
   echo gettype($ex->balance) // This returns string, not an array
endforeach

我很困惑为什么它仍然是一个字符串,而它应该是一个数组。我还在迁移中尝试了 json 而不是 text 列类型,结果相同。

最佳答案

如果您将模型配置为将属性转换为 array,则在尝试存储它时不需要将其转换回 json,Laravel 会处理这个为你。来自docs :

Array & JSON Casting

...

Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

$user = App\User::find(1);

$options = $user->options;

$options['key'] = 'value';

$user->options = $options;

$user->save();

所以在你的情况下:

$exchange = Exchange::findOrFail($id);
$exchange->balance = ['your', 'values', 'as', 'an', 'array'];
$exchange->save();

关于php - Laravel 转换数组仍然返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193794/

相关文章:

php - 无法使用 Eloquent 即时创建新表

php - 在 Laravel 表单提交上调用 Controller 函数

php - undefined offset :1- Laravel Error exception

php - 在 Google Chrome 中通过 PHP 传送 MP4 视频失败

php - CakePHP - 从表中检索最常出现的值

php - 使用 ID 数组执行单个数据库查询

javascript - 如何在 fullcalendar 中解析 json 格式的事件?

php - 这是我在 Laravel 数据库中插入多条记录的代码。那么,它不起作用吗?有人帮助我吗?

laravel - 获取条纹信用卡图像/图标 url api?

javascript - 客户端和服务器端编程有什么区别?