【问题标题】:Laravel : Bulk Insert Other and Ignore Error Exception DuplicationLaravel:批量插入其他并忽略错误异常重复
【发布时间】:2018-02-02 18:34:36
【问题描述】:

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

controller.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()); 
 }

【问题讨论】:

    标签: mysql laravel laravel-5 bulkinsert


    【解决方案1】:
    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()); 
    }
    

    【讨论】:

    • 此解决方案将执行与我的记录相同的查询;但是,我希望批量插入忽略重复错误。
    • 您好,您有解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2012-08-07
    相关资源
    最近更新 更多