gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:59:28 24 4
gpt4 key购买 nike

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

迁移

$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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com