2014-11-04 2 views
1

laravel에서 DB :: Table 또는 이와 유사한 쿼리를 실행하는 방법 ??Insert 여러 배열을 무시 하시겠습니까?

INSERT IGNORE INTO 'banban' ('column') values('value1', 'value2') 

DB::table('table')->insertIgnore(array(
    array('column'=>'value1',), 
    array('column'=>'value2') 
) 
) 

답변

0

DB::raw()를 사용하는 이외의 유창함이 작업을 수행하는 방법을 잘하지만, 설득력이 여기에 firstOrNew()

// Gets a user with fname of 'john' and lname of 'smith' or creates a new model and sets these properties. 
$user = User::firstOrNew(['fname' => 'john', 'lname' => 'smith']); 

// Lets say you want to activate john smith 
$user->activated = true; 

// Saves the new model or existing model (whatever it was) 
$user->save(); 
0

을 가지고 있지 내 \ 응용 프로그램 \ 모델의 정적 functon에 사용하고있는 코드는 삽입 무시로 여러 값을 추가하십시오. 이 코드는 StackOverflow에서 여러 가지 답을 얻었습니다.

는 테스트 및 PHP와 Laravel 5.6에서 7.1.3

$keys = ['column1', 'column2', 'column3']; 

foreach ($whatever as $result) { 
    $banban = []; 
    $banban[] = $result->value1; 
    $banban[] = $result->value2; 
    $banban[] = $result->value3; 

    $values[] = $banban; 
} 

return DB::insert(
    'INSERT IGNORE INTO ' . with(new self)->getTable() . 
    '(' . implode(',', $keys) . ') values ' . 
    substr(str_repeat('(?' . str_repeat(',?', count($keys) - 1) . '),', count($values)), 0, -1), 
    array_merge(...$values) 
); 

일부 설명 일 :

with(new self)이 모델의 새로운 인스턴스를 반환합니다. 정적 함수에서 Model 테이블 이름을 얻는 쉬운 방법입니다.

substr(...,0,-1)

는 "값"

str_repeat은 "(?,?,?)"자리를 만들기 위해 두 번 사용하고 "?"입니다의 최신 쉼표를 제거하는 데 사용됩니다 내부.

array_merge(...$values) flatters 값의 배열입니다. 따라서 $values에는 사용자 지정 키를 사용할 수 없습니다.

희망이 도움이됩니다.

관련 문제