当检索列时,我想将其作为数组获取,但它作为字符串返回。
迁移
$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 theoptions
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/