How to insert multiple rows of a single query using the same ID

Asked

Viewed 181 times

1

I’m trying to make multiple Inserts using the same ID with the Laravel but it is doing only 1 Insert.

The idea would be something like this.

ped_cod|est_cod|ped_qtde
    8  |2      |9
    8  |3      |2
    8  |4      |2
    8  |9      |15

MODEL

class EstoqueDet extends Model
{
    protected $table = 'public.estoque_det';
    protected $primaryKey = 'ped_cod';
}

CONTROLLER (I check if the input is bringing something if I do Insert)

$caneta  = $this->request->get('caneta_input');
$sulfite = $this->request->get('sulfite_input');
$tonner = $this->request->get('tonner_input');
$pasta = $this->request->get('pasta_input');



$estoqdet = $this->estoqueDet; 


if(isset($caneta)) {

    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_caneta;
    $estoqdet->ped_qtde = $caneta;
    $estoqdet->save([$estoqdet]);



}

if(isset($sulfite)) {

    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_sulfite;
    $estoqdet->ped_qtde = $sulfite;
    $estoqdet->save([$estoqdet]);


}

if(isset($tonner)) {

    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_tonner;
    $estoqdet->ped_qtde = $tonner;
    $estoqdet->save([$estoqdet]);


}

if(isset($pasta)) {

    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_pasta;
    $estoqdet->ped_qtde = $pasta;
    $estoqdet->save([$estoqdet]);


}
  • Does it give any error? It may be because you will not be able to insert more than one record with the same Primary key, as it should be unique.

  • There is no error in the other application that is with PHP structured it inserts quiet

  • So try to take this line protected $primaryKey = 'ped_cod';

  • I took and it starts giving the error Undefined column: 7 ERROR: column "id" does not exist

  • Well, I don’t know if you can reset the bank, but maybe it would be interesting for you to create the column id as Primary key, and the others as normal columns. In this case would insert normally.

1 answer

1


You need to create a new instance every new record you want to create, in your case you are just changing the same record N times.

if(isset($caneta)) {
    $estoqdet = new EstoqueDet();
    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_caneta;
    $estoqdet->ped_qtde = $caneta;
    $estoqdet->save([$estoqdet]);
}

if(isset($sulfite)) {
    $estoqdet = new EstoqueDet();
    $estoqdet->ped_cod = $pedido_id;
    $estoqdet->est_cod = $cod_sulfite;
    $estoqdet->ped_qtde = $sulfite;
    $estoqdet->save([$estoqdet]);
}
  • 1

    Perfect @Jardel was that very thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.