使用Laravel一次插入多个记录 [英] Insert Multiple Records At Once With Laravel

查看:168
本文介绍了使用Laravel一次插入多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据一一插入到行中,但是我听说某个地方如果要插入许多数据,则需要很多时间.那么一次将它们全部插入的方式又是什么呢?

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 them all at once?

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

推荐答案

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;

这篇关于使用Laravel一次插入多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆