简体   繁体   English

Laravel-从JSON数组创建对象以将其保存在SQL数据库中

[英]Laravel - Creating an object from a JSON array to save it in a SQL database

What I am trying to do is to send a JSON array (that was gotten from Guzzle) to my SQL database. 我想做的是将JSON数组(从Guzzle获取)发送到我的SQL数据库。 I have gotten to the point where I am able to get the response and display the gotten JSON array on a webpage. 我已经到了可以获取响应并在网页上显示获取的JSON数组的地步。 The array is defined as the $data variable. 该数组定义为$data变量。 The $data variable gets decoded using this: $data变量使用以下方法解码:

$data = json_decode($response->getBody()->getContents());

This is able to get the JSON and decode it with no problem. 这样就可以毫无问题地获取JSON并将其解码。 The part I am stuck on is taking the $data variable, processing it and sending it to my database. 我遇到的问题是获取$data变量,对其进行处理并将其发送到我的数据库。 From what I understand is that you are required to convert the JSON into an array and then send it to the database. 据我了解,您需要将JSON转换为数组,然后将其发送到数据库。

The JSON format is like this: 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"
}]

My Satellite Model goes like this: 我的卫星模型如下:

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'
]; 

My migrations file: 我的迁移文件:

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

I tried making an $object array, which did not work. 我尝试制作一个$object数组,该数组不起作用。

TL;DR: I want to take the $data variable, which contains the decoded JSON and create something that allows it to get saved into my 'satellites' SQL database. TL; DR:我想获取$data变量,该变量包含已解码的JSON,并创建一些内容使其可以保存到我的“卫星” SQL数据库中。

EDIT: Here is the full Satellite controller: 编辑:这是完整的Satellite控制器:

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

It looks like your JSON key names match up nicely with your model attributes, with the exception of being capitalised. 看起来您的JSON关键字名称与您的模型属性很好地匹配,但大写除外。

Try mapping the data keys to lowercase and then creating your model instance. 尝试将数据键映射为小写,然后创建模型实例。 Per @OmisakinOluwatobi suggestion, you can use pass true to json_decode to retrieve the data as an array. 根据@OmisakinOluwatobi的建议,您可以将true传递给json_decode来以数组形式检索数据。

Edit - I missed that your response data was an array of objects. 编辑 -我错过了您的响应数据是一个对象数组。 The following update will iterate over the response data and create a new Satellite for each. 以下更新将迭代响应数据并为每个响应数据创建一个新的Satellite

// Retrieve data from response
$data = json_decode($response->getBody()->getContents(), true);

// Iterate over response data
foreach ($data as $attributes) {
    // Change attribute keys to lowercase
    $attributes = array_change_key_case($attributes, CASE_LOWER);

    // Create satellite model
    Satellite::create($attributes);
}

It is actually as simple as $encoded = json_encode($request->your_array); 实际上就像$encoded = json_encode($request->your_array);一样简单$encoded = json_encode($request->your_array); . This $encoded will now be "savable" to sql database. 现在,此$encoded可以“保存”到sql数据库中。 When you later access the encoded data, you can use a JSON parser to convert back to a json array. 以后访问编码数据时,可以使用JSON解析器将其转换回JSON数组。 Example using jQuery var your_array = $.parseJSON($response.body); 使用jQuery的示例var your_array = $.parseJSON($response.body);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM