使用Laravel一次插入多个记录

时间:2016-08-24 02:55:03

标签: php laravel

我将数据逐个插入到行中,但是我听说过如果要插入许多数据需要很多时间。那么一次插入它们的方法是什么?

public function add(Request $request)
{
    if ($request->ajax()) {
        $books = $request->books;
        foreach ($books as $book) {
            if (!empty($book)) {
                $add = new Book;
                $add->name = $book;
                $add->user_id = Auth::user()->id;
                $add->save();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:12)

public function add(Request $request)
  {
    if($request->ajax())
    {
       $books=$request->books;
       $data = array();
       foreach($books as $book)
       {
        if(!empty($book))
        {
          $data[] =[
                    'name' => $book,
                    'user_id' => Auth::id(),
                   ];                 

       }}
      Book::insert($data);
       <!--DB::table('books')->insert($data);-->
     }}

确保导入use Illuminate\Support\Facades\Auth;

答案 1 :(得分:11)

使用Model

插入多个记录

正如其他人所指出的那样,使用查询生成器是一次插入多个记录的唯一方法。幸运的是,Laravel和Eloquent ORM以许多有用的方式结合在一起。这种耦合允许您使用Model来获取为该模型设置的Query Builder实例。

// 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);
    }
}

答案 2 :(得分:3)

您应该可以执行以下操作:

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

将要插入的所有值放入数组中,然后将其传递给插入函数。

来源:https://laravel.com/docs/5.1/queries#inserts