Laravel
[Laravel] updateOrInsert
먹세
2022. 4. 6. 12:58
데이터가 존재하면 Update, 없으면 Insert 하는 기능
DB::table('users')
->updateOrInsert(
['email' => 'john@example.com', 'name' => 'John'], //조건
['votes' => '2'] //update 또는 insert 데이터
);
email 과 name 이 조건과 일치하는 데이터가 존재할경우, votes를 업데이트한다.
데이터가 없을경우 새로 insert 한다.
주의 : Eloquent ORM 사용시 timestamp가 설정되어 있더라도 created_at, updated_at 자동적용 안됨
Laravel 8+ 부터는 upsert 메소드 생김
여러행의 row를 삽입 가능
DB::table('flights')->upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], // update 또는 insert 할 데이터 rows
['departure', 'destination'], // 조건
['price'] // update 또는 insert 할 컬럼
);
반응형