laravel - 在 Laravel 8 中持久化数组数据
问题描述
我有一个这样的数组结构:
数据是这样生成的:-
$allBreeds = json_decode($response->getBody()->getContents());
$i = 0;
foreach($allBreeds->message as $breed => $types){
$this->breeds[$i]['name'] = $breed;
if(!empty($types)){
$this->breeds[$i]['types'] = json_encode($types);
} else {
$this->breeds[$i]['types'] = [];
}
$i++;
}
我的数据库架构是这样的: -
Schema::create('breeds', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->json('types')->default(null);
$table->timestamps();
});
create table `breeds` (
`id` bigint (20),
`name` varchar (765),
`types` varchar (-1),
`created_at` timestamp ,
`updated_at` timestamp
);
使用 eloquent 的成功插入看起来类似于:-
$testBreeds = [
['name' => 'hound', 'types' => json_encode([0 => 'afgan', 1 => 'basset', 2 => 'blood'])],
['name' => 'chihuahua', 'types' => json_encode([])],
];
Breed::insert($testBreeds);
如何规范化我的数据以将其持久化/插入到breeds
数据库表中 - 即如何删除索引?如果我尝试按原样插入它- 我会收到一个数组到字符串转换错误。
解决方案
该错误是此代码块的结果:
if(!empty($types)){
$this->breeds[$i]['types'] = json_encode($types);
} else {
$this->breeds[$i]['types'] = [];
}
如果它不为空,您正在json_encode
-ing 的值$types
,否则将其设置为空数组而不是json_encode
-ing 它并且您不能将数组插入json
列中。
执行以下操作之一:
更新您的迁移以null
接受$types
;
$table->json('types')->nullable()->default(null);
$this->breeds[$i]['types'] = null;
if(!empty($types)){
$this->breeds[$i]['types'] = json_encode($types);
}
或者,即使它是空的,也总是json_encode
该值。$types
$this->breeds[$i]['types'] = json_encode($types);
推荐阅读
- arduino - 使用通过 CAN 总线发送的信息在 Arduino 上闪烁 LED 时出现问题
- symfony - 如何使用 Symfony 解决 URL 中的 ID 传递问题
- for-loop - 测试数组/列表的所有元素是否满足条件的最佳方法
- postgresql - 访问列数组并将其存储在新表中
- c# - 使用百分比,我如何获得两个日期时间之间的时间?
- javascript - 响应式可折叠表一次一张:
- python - 如何在tweepy中过滤关键字搜索
- sql - 如何在 SQL 中聚合数量?
- python - 为什么 pip install 缺少我的软件包的源?
- java - 无法为 ascii 图像获取正确的基本输出