0

I have a problem saving a json result to a table in the mysql database.

Json Return

{ "retorno": {
  "status_processamento": 3,
    "status": "OK",
    "pagina": "1",
    "numero_paginas": "1",
    "pedidos": [
      {
        "pedido": {
          "id": 123456,
          "numero": 123456,
          "numero_ecommerce": "12",
          "data_pedido": "01/01/2013",
          "data_prevista": "10/01/2013",
          "nome": "Cliente Teste",
          "valor": "100.25",
          "id_vendedor": "123456",
          "nome_vendedor": "Vendedor Teste",
          "situacao": "Atendido"
        }
      },
      {
        "pedido": {
          "id": 123456,
          "numero": 123458,
          "numero_ecommerce": "15",
          "data_pedido": "01/01/2013",
          "data_prevista": "10/01/2013",
          "nome": "Cliente Teste 3",
          "valor": "50.25",
          "id_vendedor": "",
          "nome_vendedor": "",
          "situacao": "Aberto"
        }
      }
    ]
  }
}

Model

namespace App;

use Illuminate\Database\Eloquent\Model;
class Rating extends Model
{

 protected $fillable = [

          'ratingKey'

      ];

}

Controller

  $data = json_decode($response, true);

  Rating::create(
  [ 'ratingKey'  => $data['retorno']['pedidos'][0]['pedido']['id']   ]);

this code works perfectly but only saves one answer from json and i would like to save all the answers and if i change the code to

'ratingKey'  => $data['retorno']['pedidos'][]['pedido']['id'] 

I get this error

Symfony\Component\Debug\Exception\FatalErrorException Cannot use [] for reading

1
  • This syntax: $data['retorno']['pedidos'][]['pedido']['id'] won't work. You'll need to use some kind of loop iterate the data and construct a viable array for insertion, or insert one-by-one in said loop. Commented Dec 23, 2019 at 21:34

1 Answer 1

1

You simply need to iterate over your $data['retorno']['pedidos'] array creating a structured array of arrays to be passed to the Rating::insert() method (docs).

$data = json_decode($response, true);

$ratingKeys = [];
foreach($data['retorno']['pedidos'] as $o){
    $ratingKeys[] = ['ratingKey' => $o['pedido']['id']];
}

Rating::insert($ratingKeys);
Sign up to request clarification or add additional context in comments.

3 Comments

Call to undefined method App\Rating::createMany()
@LucasSilva Updated answer.
const VERSION = '6.8.0';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.