Insert Multiple Records At Once With Laravel

前端 未结 4 1307
栀梦
栀梦 2021-01-05 09:14

I am inserting the data to the rows one by one, but I have heard somewhere that it requires much time if there are many data to insert. So what are the ways of inserting the

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 09:55

    Insert multiple records using the Model

    As others have pointed out, using the Query Builder is the only way to insert multiple records at a time. Fortunately Laravel and the Eloquent ORM are coupled in many useful ways. This coupling allows you to use a Model to get a Query Builder instance that is set for that Model.

    // use Auth;
    // use Carbon;
    // use App\Book;
    
    public function add(Request $request)
    {
        if($request->ajax())
        {
            // Submitted books
            $books = $request->books;
    
            // Book records to be saved
            $book_records = [];
    
            // Add needed information to book records
            foreach($books as $book)
            {
                if(! empty($book))
                {
                    // Get the current time
                    $now = Carbon::now();
    
                    // Formulate record that will be saved
                    $book_records[] = [
                        'name' => $book,
                        'user_id' => Auth::user()->id,
                        'updated_at' => $now,  // remove if not using timestamps
                        'created_at' => $now   // remove if not using timestamps
                    ];
                }
            }
    
            // Insert book records
            Book::insert($book_records);
        }
    }
    

提交回复
热议问题