首页 > 解决方案 > 在 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数据库表中 - 即如何删除索引?如果我尝试按原样插入它- 我会收到一个数组到字符串转换错误。

标签: laraveleloquent

解决方案


该错误是此代码块的结果:

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);

推荐阅读