在Laravel 4中打开DUPLICATE KEY UPDATE查询

时间:2014-05-06 13:12:44

标签: mysql laravel-4 sql-update sql-insert

如何转换此

DB::table('partners')->insert(array($data));

laravel查询ON DUPLICATE KEY UPDATE

结构看起来像

$data['program_name'] = $program['program']['_'];
$data['program_id'] = $program_id;
$data['status'] = $program['status'];
$data['shop_name'] = $shop->name;
$data['shop_logo'] = $shop->image;
$data['shop_description'] = $shop->description;

其中program_id是唯一的

2 个答案:

答案 0 :(得分:3)

使用类似的东西(随意更正,因为它未经测试):

DB::statement( 'INSERT INTO partners VALUES (' . implode( ',',
    array_map( function( $val ) { return ":$val"; } , array_keys($data) )
) . ') ON DUPLICATE KEY UPDATE ' . implode( ',',
    array_map( function( $val ) { return "$val = VALUES($val)"; } , array_keys($data) )
), $data);

答案 1 :(得分:0)

我创建了一个包裹INSERT ON DUPLICATE KEY UPDATE

的包

https://packagist.org/packages/yadakhov/insert-on-duplicate-key

$users = [
   ['id' => 1, 'email' => 'user1@email.com', 'name' => 'User One'],
   ['id' => 2, 'email' => 'user2@email.com', 'name' => 'User Two'],
   ['id' => 3, 'email' => 'user3@email.com', 'name' => 'User Three'],
];

User::insertOnDuplicateKey($users);

// produces:

INSERT INTO `test_user_table`(`id`,`email`,`name`) VALUES
(1,'user1@email.com','User One'), (2,'user3@email.com','User Two'), (3,'user3email.com','User Three')
ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `email` = VALUES(`email`), `name` = VALUES(`name`)