Laravel 在查询 JSONB 列(转换为数组)时是否调用一次或多次 json_decode?

Does Laravel calls json_decode once or more when querying JSONB column (cast to array)?

根据 documentation,我可以使用 Laravel 将 JSONB 列转换为数组。这很棒,但我想了解它是如何工作的。因为我不知道它在这段代码中调用了一次还是多次json_decode(假设metadata是一个JSONB列):

echo $user->metadata['field_a'];
echo $user->metadata['field_b'];
echo $user->metadata['field_c'];

Laravel 调用 json_decode 一次还是三次?

如果是这样,我应该用这个替换我的代码吗?

$meta = $user->metadata;
echo $meta['field_a'];
echo $meta['field_b'];
echo $meta['field_c'];

旁注:这不是关于微优化的问题。有时我会在大循环中多次调用 JSONB,所以也许我需要全部重写。

当数据来自数据库时,

Laravel 将执行一次所有转换。所有 eloquent 数据库函数都将使用 fill function to set the properties of a model. And this function will set the attributes using the setAttribute 函数。

setAttribute 函数将检查强制转换并相应地设置对象的属性。所以 json 被解码一次,然后作为对象或数组设置到 属性.

Json 字符串在 setAttribute 函数中转换为 here