【发布时间】:2026-01-21 22:50:01
【问题描述】:
我想要做的是将一个 JSON 数组(从 Guzzle 获得)发送到我的 SQL 数据库。我已经到了能够获得响应并在网页上显示获得的 JSON 数组的地步。该数组被定义为$data 变量。 $data 变量使用以下代码解码:
$data = json_decode($response->getBody()->getContents());
这可以毫无问题地获取 JSON 并对其进行解码。我坚持的部分是获取$data 变量,对其进行处理并将其发送到我的数据库。据我了解,您需要将 JSON 转换为数组,然后将其发送到数据库。
JSON格式是这样的:
[{
"INTLDES": "2017-042Z",
"NORAD_CAT_ID": "42848",
"OBJECT_TYPE": "TBA",
"SATNAME": "OBJECT Z",
"COUNTRY": "TBD",
"LAUNCH": "2017-07-14",
"SITE": "TTMTR",
"DECAY": null,
"PERIOD": "96.52",
"INCLINATION": "97.61",
"APOGEE": "597",
"PERIGEE": "586",
"COMMENT": null,
"COMMENTCODE": null,
"RCSVALUE": "0",
"RCS_SIZE": null,
"FILE": "6242",
"LAUNCH_YEAR": "2017",
"LAUNCH_NUM": "42",
"LAUNCH_PIECE": "Z",
"CURRENT": "Y",
"OBJECT_NAME": "OBJECT Z",
"OBJECT_ID": "2017-042Z",
"OBJECT_NUMBER": "42848"
}]
我的卫星模型是这样的:
protected $fillable = [
'intldes',
'norad_cat_id',
'object_type',
'satname',
'country',
'launch',
'site',
'decay',
'period',
'inclination',
'apogee',
'perigee',
'comment',
'commentcode',
'rcsvalue',
'rcs_size',
'file',
'launch_year',
'launch_num',
'launch_piece',
'current',
'object_name',
'object_id',
'object_number'
];
我的迁移文件:
Schema::create('satellites', function (Blueprint $table) {
$table->increments('id');
$table->string('intldes');
$table->string('norad_cat_id');
$table->string('object_type');
$table->string('satname');
$table->string('country');
$table->string('launch')->nullable();
$table->string('site')->nullable();
$table->string('decay')->nullable();
$table->string('period')->nullable();
$table->string('inclination')->nullable();
$table->string('apogee')->nullable();
$table->string('perigee')->nullable();
$table->string('comment')->nullable();
$table->string('commentcode')->nullable();
$table->string('rcsvalue')->nullable();
$table->string('rcs_size')->nullable();
$table->string('file')->nullable();
$table->string('launch_year')->nullable();
$table->string('launch_num')->nullable();
$table->string('launch_piece')->nullable();
$table->string('current')->nullable();
$table->string('object_name');
$table->string('object_id');
$table->string('object_number');
$table->timestamps();
});
我尝试创建一个$object 数组,但没有成功。
TL;DR:我想获取包含解码后的 JSON 的 $data 变量,并创建一些允许它保存到我的“卫星”SQL 数据库中的内容。
编辑:这是完整的卫星控制器:
public function displayer(){
$api = new Client([
'base_uri' => 'https://www.space-track.org',
'cookies' => true,
]); $api->post('ajaxauth/login', [
'form_params' => [
'identity' => '#',
'password' => '#',
],
]);
$response = $api->get('basicspacedata/query/class/satcat/orderby/INTLDES%20desc/limit/5/metadata/false');
$data = json_decode($response->getBody()->getContents(), true);
$data = array_change_key_case($data, CASE_LOWER);
$model = Satellite::create($data);
dd($data);
}
【问题讨论】:
-
这可能与问题无关,但是 $fillable 的长数组可以更改为
protected $guarded = ['id'];(而不是)仅将id列入黑名单,而其他人则可以批量分配。 -
@OmisakinOluwatobi 现在将编辑它!
-
您实际上不必编辑,只为任何觉得有用的人,您的代码已经可以了
标签: php sql arrays json laravel