使用Laravel一次插入多条记录

093gszye  于 2023-08-08  发布在  其他
关注(0)|答案(5)|浏览(142)

我正在一行一行地插入数据,但我听说如果有很多数据要插入,则需要很长时间。那么有什么方法可以一次把它们都插进去呢?

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

字符串

eivgtgni

eivgtgni1#

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;

svujldwt

svujldwt2#

使用Model插入多条记录

正如其他人所指出的,使用查询构建器是一次插入多条记录的唯一方法。幸运的是,Laravel和Eloquent ORM以许多有用的方式耦合在一起。这种耦合允许您使用Model来获取为该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);
    }
}

字符串

2ul0zpep

2ul0zpep3#

你应该可以做下面这样的事情:

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

字符串
将所有要插入的值放入数组中,然后将其传递给insert函数。
来源:https://laravel.com/docs/5.1/queries#inserts

ha5z0ras

ha5z0ras4#

foreach($request->refereename as $i =>$value)
  {
    $referees[]=[
        'refereename'=>$request->refereename[$i],
        'refereecompany'=>$request->refereecompany[$i],
        'refereephone'=>$request->refereephone[$i],
        'refereeemail'=>$request->refereeemail[$i],
        'relationship'=>$request->relationship[$i],
        'refereelocation'=>$request->refereelocation[$i],
        'created_at'=>$date,
        'updated_at'=>$date,
        ];
  }

  DB::table('db_referees')->insert($referees); // Query Builder approach

字符串

mkh04yzy

mkh04yzy5#

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

相关问题