【问题标题】:Insert Multiple Records At Once With Laravel使用 Laravel 一次插入多条记录
【发布时间】:2016-12-31 00:29:46
【问题描述】:

我正在将数据逐行插入,但我在某处听说,如果要插入很多数据,则需要很长时间。那么有什么方法可以一次性全部插入呢?

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

【问题讨论】:

标签: php laravel


【解决方案1】:

使用模型插入多条记录

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

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

【讨论】:

  • 这太糟糕了,你发布了我的 @Qevo 的副本
【解决方案2】:
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;

【讨论】:

    【解决方案3】:

    如果您需要 Eloquent model events - 没有其他方法可以插入多个模型。以其他方式-检查Anushan W答案

    【讨论】:

      【解决方案4】:

      您应该能够执行以下操作:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-16
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        相关资源
        最近更新 更多