Monday, April 3, 2017

Laravel 5.2 Builder insert replace multiple rows

i have this code, can insert an array at first time, but when trying replace and update, return msg error " Integrity constraint violation: 1062 Duplicate entry" for composite key ['periodo_id','asociado_id']

Model:

<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Lectura extends Model
 {
  protected $primaryKey = array('periodo_id', 'asociado_id');
  public $timestamps = false;
  public $incrementing = false;
    public function asociado()
    {
        return $this->belongsTo('App\Asociado');
    }
    public function periodo()
    {
        return $this->belongsTo('App\Periodo');
    }       
  }

And controller:

        $rows = DB::table('lecturas_temp')->get(); 
        $arr = array();
        foreach ($rows as $row) {
           $a = [
                'asociado_id' => $row->asociado_id,
                'periodo_id'  => $request->periodo_id,
                'nombre'      => $row->nombre,
            ];
           array_push($arr, $a);
        }
        DB::table('lecturas')->insert($arr);

Any alternatives to line DB::table('lecturas')->insert($arr)? I tried Eloquent Lectura::insert($arr) and updateOrCreate but same results;



via Alejandro Beltran

Advertisement