我正在尝试将JSON字段转换为数组.例如,模型是这样的:
protected $casts = [ 'content' => 'array' ];
在插入内容时,我这样做:
'content'=> json_encode([ 'description' => $faker->paragraph(3), 'about' => $faker->paragraph(2), 'info' => $faker->paragraph(2), 'updated' => $faker->dateTimeBetween('-1 years', 'now') ]),
但在获取数据时,它会打印一个字符串,而不是其他内容.
此部分中的迁移如下所示:
$campaign->json('content');
输出样本:
"content": "{\"description\":\"Ut quas quo odio illo. Voluptates quia fuga itaque sint. Velit sapiente fugit ea ut ducimus sint tempora eligendi. Ea et molestiae consequuntur quibusdam soluta voluptatem.\",\"about\":\"Aut voluptates et iste ut perspiciatis. Esse sunt ullam inventore sit doloremque et quisquam.\",\"info\":\"Corrupti et facere exercitationem consequatur aspernatur quo saepe. Omnis et tempore enim ut. Quia magnam quia enim et eos enim.\",\"updated\":{\"date\":\"2015-11-22 08:25:13.000000\",\"timezone_type\":3,\"timezone\":\"UTC\"}}",
有什么想法吗?
定义array
演员表时,您不需要做任何json_encode
或json_decode
.当你想插入时,你需要做的很简单:
'content'=> [ 'description' => $faker->paragraph(3), 'about' => $faker->paragraph(2), 'info' => $faker->paragraph(2), 'updated' => $faker->dateTimeBetween('-1 years', 'now') ],
Laravel将完成剩下的工作
当你想获得content
现场数据时,你只需要使用:
$campaign->content;
你将在这里有数组,所以如果你想显示描述,你只需要做:
echo $campaign->content['description'];