2017-04-04 72 views
0

我有此代碼,可以在第一次插入一個數組,而是試圖替換和更新時,它會返回錯誤Laravel 5.2 Builder中插入替換多行

完整性約束違規:1062重複條目組合鍵[ 'periodo_id', 'asociado_id']

型號:

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

和控制器:

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

任何替代品線DB::table('lecturas')->insert($arr)

我試過Eloquent Lectura::insert($arr)updateOrCreate但結果相同;

+0

爲什麼你有兩個主鍵? – linktoahref

+0

我有id如何整數10 autoincrement,我發現它適合從csv導入並使用這兩列作爲鍵「插入替換」 –

回答

1

錯誤信息非常清晰。您正在使用複合鍵['periodo_id', 'asociado_id'],這意味着您無法兩次插入相同的數據,因爲您已將其定義爲主鍵。

如果您希望有複製組合鍵,請將其從模型中作爲主鍵移除。但是,如果您希望數據是唯一的,則應使用updateOrCreate()。您可以看到updateOrCreate()需要2個數組作爲參數。第一個數組是用於驗證它是否已經存在的元素。另外,不幸的是,你必須一個接一個地做,而不是像你一樣去做。

如果您想堅持查詢生成器,可以使用DB::updateOrInsert(),使用相同的調用簽名(傳遞2個數組)。

+0

謝謝,但$ rows是一個包含多行的數組。我嘗試過,但只做每個循環(一個插入,每個循環)。我可以在Model Lectura中使用https://github.com/yadakhov/insert-on-duplicate-key解決問題 –

0

使用此代碼我沒解決:https://github.com/yadakhov/insert-on-duplicate-key

class Lectura extends Model 
{ 

    protected $primaryKey = array('periodo_id', 'asociado_id'); 
    public $timestamps = false; 
    public $incrementing = false; 


public static function insertOnDuplicateKey(array $data, array $updateColumns = null) 
{ 
    if (empty($data)) { 
     return false; 
    } 
    // Case where $data is not an array of arrays. 
    if (!isset($data[0])) { 
     $data = [$data]; 
    } 
    $sql = static::buildInsertOnDuplicateSql($data, $updateColumns); 
    $data = static::inLineArray($data); 
    return self::getModelConnectionName()->affectingStatement($sql, $data); 
} 
/** 
* Insert using mysql INSERT IGNORE INTO. 
* 
* @param array $data 
* 
* @return int 0 if row is ignored, 1 if row is inserted 
*/ 
public static function insertIgnore(array $data) 
{ 
    if (empty($data)) { 
     return false; 
    } 
    // Case where $data is not an array of arrays. 
    if (!isset($data[0])) { 
     $data = [$data]; 
    } 
    $sql = static::buildInsertIgnoreSql($data); 
    $data = static::inLineArray($data); 
    return self::getModelConnectionName()->affectingStatement($sql, $data); 
} 
/** 
* Insert using mysql REPLACE INTO. 
* 
* @param array $data 
* 
* @return int 1 if row is inserted without replacements, greater than 1 if rows were replaced 
*/ 
public static function replace(array $data) 
{ 
    if (empty($data)) { 
     return false; 
    } 
    // Case where $data is not an array of arrays. 
    if (!isset($data[0])) { 
     $data = [$data]; 
    } 
    $sql = static::buildReplaceSql($data); 
    $data = static::inLineArray($data); 
    return self::getModelConnectionName()->affectingStatement($sql, $data); 
} 
/** 
* Static function for getting table name. 
* 
* @return string 
*/ 
public static function getTableName() 
{ 
    $class = get_called_class(); 
    return (new $class())->getTable(); 
} 
/** 
* Static function for getting connection name 
* 
* @return string 
*/ 
public static function getModelConnectionName() 
{ 
    $class = get_called_class(); 
    return (new $class())->getConnection(); 
} 
/** 
* Get the table prefix. 
* 
* @return string 
*/ 
public static function getTablePrefix() 
{ 
    return self::getModelConnectionName()->getTablePrefix(); 
} 
/** 
* Static function for getting the primary key. 
* 
* @return string 
*/ 
public static function getPrimaryKey() 
{ 
    $class = get_called_class(); 
    return (new $class())->getKeyName(); 
} 
/** 
* Build the question mark placeholder. Helper function for insertOnDuplicateKeyUpdate(). 
* Helper function for insertOnDuplicateKeyUpdate(). 
* 
* @param $data 
* 
* @return string 
*/ 
protected static function buildQuestionMarks($data) 
{ 
    $lines = []; 
    foreach ($data as $row) { 
     $count = count($row); 
     $questions = []; 
     for ($i = 0; $i < $count; ++$i) { 
      $questions[] = '?'; 
     } 
     $lines[] = '(' . implode(',', $questions) . ')'; 
    } 
    return implode(', ', $lines); 
} 
/** 
* Get the first row of the $data array. 
* 
* @param array $data 
* 
* @return mixed 
*/ 
protected static function getFirstRow(array $data) 
{ 
    if (empty($data)) { 
     throw new \InvalidArgumentException('Empty data.'); 
    } 
    list($first) = $data; 
    if (!is_array($first)) { 
     throw new \InvalidArgumentException('$data is not an array of array.'); 
    } 
    return $first; 
} 
/** 
* Build a value list. 
* 
* @param array $first 
* 
* @return string 
*/ 
protected static function getColumnList(array $first) 
{ 
    if (empty($first)) { 
     throw new \InvalidArgumentException('Empty array.'); 
    } 
    return '`' . implode('`,`', array_keys($first)) . '`'; 
} 
/** 
* Build a value list. 
* 
* @param array $first 
* 
* @return string 
*/ 
protected static function buildValuesList(array $first) 
{ 
    $out = []; 
    foreach (array_keys($first) as $key) { 
     $out[] = sprintf('`%s` = VALUES(`%s`)', $key, $key); 
    } 
    return implode(', ', $out); 
} 
/** 
* Inline a multiple dimensions array. 
* 
* @param $data 
* 
* @return array 
*/ 
protected static function inLineArray(array $data) 
{ 
    return call_user_func_array('array_merge', array_map('array_values', $data)); 
} 
/** 
* Build the INSERT ON DUPLICATE KEY sql statement. 
* 
* @param array $data 
* @param array $updateColumns 
* 
* @return string 
*/ 
protected static function buildInsertOnDuplicateSql(array $data, array $updateColumns = null) 
{ 
    $first = static::getFirstRow($data); 
    $sql = 'INSERT INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; 
    $sql .= static::buildQuestionMarks($data) . PHP_EOL; 
    $sql .= 'ON DUPLICATE KEY UPDATE '; 
    if (empty($updateColumns)) { 
     $sql .= static::buildValuesList($first); 
    } else { 
     $sql .= static::buildValuesList(array_combine($updateColumns, $updateColumns)); 
    } 
    return $sql; 
} 
/** 
* Build the INSERT IGNORE sql statement. 
* 
* @param array $data 
* 
* @return string 
*/ 
protected static function buildInsertIgnoreSql(array $data) 
{ 
    $first = static::getFirstRow($data); 
    $sql = 'INSERT IGNORE INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; 
    $sql .= static::buildQuestionMarks($data); 
    return $sql; 
} 
/** 
* Build REPLACE sql statement. 
* 
* @param array $data 
* 
* @return string 
*/ 
protected static function buildReplaceSql(array $data) 
{ 
    $first = static::getFirstRow($data); 
    $sql = 'REPLACE INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; 
    $sql .= static::buildQuestionMarks($data); 
    return $sql; 
} 

在控制器

Lectura::replace($arr);