Bulk insert and get returned ids laravel

前端 未结 2 950
名媛妹妹
名媛妹妹 2021-01-19 09:19

I have an array like this one :

 0 => array:2 [
    \"name\" => \"Data1\"
    \"type\" => \"value1\"
  ],
 1 => array:2 [
    \"name\" => \"Da         


        
2条回答
  •  离开以前
    2021-01-19 09:51

    I use this method to insert non-duplicate data.

    But this method consumes performance.

    class TestController extends Controller
    {
        public function test()
        {
    
            DB::transaction(function () {
    
                $insertedIds = [];
                //the name key is unique, so i use the firstOrCreate method
                for ($i = 0; $i < 10; $i++) {
                    $tag = Tags::firstOrCreate(['name' => 30 + $i]);
                    $id = $tag->id;
                    array_push($insertedIds, $id);
                }
    
                dump($insertedIds);
            });
    
        }
    }
    
    

提交回复
热议问题