Laravel:批量插入其他并忽略错误异常重复

问题描述 投票:0回答:1

在 mysql 中,我在列

url
上设置了唯一键,在 Laravel 控制器中,我创建了数组的键值对以准备批量插入。我想通过忽略错误重复异常插入,但为其他人插入。我有以下代码:

控制器.php

try{
    $container = array();
    foreach ($js->RECORDS as $rec) {
        $data = [
         'title'=>$rec->title,
         'description'=>$rec->description,
         'url'=>$rec->url
        ];
       array_push($container, $data);
    }
    $status = Model::insert($container);
 }catch (\Exception $e){
   $req->session()->flash('alert-danger', $e->getMessage()); 
 }
php mysql laravel laravel-5 bulkinsert
1个回答
0
投票
try{
    foreach ($js->RECORDS as $rec) {
        $data = [
         'title'=>$rec->title,
         'description'=>$rec->description,
         'url'=>$rec->url
        ];
    $status = Model::updateOrCreate(['url' => $rec->url], $data);
   }
}catch (\Exception $e){
   $req->session()->flash('alert-danger', $e->getMessage()); 
}
© www.soinside.com 2019 - 2024. All rights reserved.