【发布时间】:2019-02-05 09:06:33
【问题描述】:
我创建的用一行填充数据库的模拟不理解它需要在将数据存储到数据库之前将数据转换为 JSON。出于某种原因,当来自模拟的数据插入数据库时,它会跳过转换为 JSON。因此,当逻辑随后从数据库中获取行时,它会返回此错误。
json_decode() expects parameter 1 to be string, array given
如果我将它作为模拟中的数组。当我们在控制器中解码时会产生这个错误。 如果我在模拟中对其进行编码,它会返回相同的错误。 如果我在模拟中对其进行编码并从模型中移除演员表,它会按预期工作。
有谁知道如何正确地做到这一点?
这是我的模拟
class SettingMocks
{
public static function getSetting() {
return [
'id' => 1,
'name' => 'Standard',
'settings' => json_encode([
'objective' => "CONVERSIONS",
'gender' => [1,2],
])
];
}
}
这是我的模特
class Setting extends Model
{
protected $guarded = [];
protected $casts = [
'settings' => 'json',
];
}
【问题讨论】:
-
仔细阅读文档。您可能需要使用 toJson() 或者它用于序列化的 json 。 laravel.com/docs/5.7/eloquent-mutators#attribute-casting
标签: php laravel unit-testing functional-testing codeception