如何在Laravel5中使用Eloquent在数据库中插入多行

时间:2015-11-10 09:56:19

标签: laravel laravel-5.1

我的控制器看起来像这样

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\Http\Middleware\Role;
    use Illuminate\Support\Facades\Input;
    use App\Http\Requests\PaymentRequest;
    use App\User;
    use App\Invoice;
    use App\comments;
    use Session;
    use Validator;


    class CollectionController extends Controller
    {
        /**
         * Display a listing of the resource.
         *
         * @return Response
         */

      public function __construct(){

        $this->middleware('role:collector'); // replace 'collector' with whatever role you need.
    }


  public function postPayment(PaymentRequest $request){

          $insertPayment=Input::get();

          $payment= new paymentrecieved();
          $comment= new comments();

          $payment->invoice_id=$insertPayment['invoiceid'];
          $payment->recieved_amount=$insertPayment['recieved_amount'];
          $payment->refno=$insertPayment['ref_no'];
          $payment->date=$insertPayment['date'];

         if($insertPayment['adjustmentmode']=='Option')
          $payment->adjust_mode='NONE';
          else
            $payment->adjust_mode=$insertPayment['adjustmentmode'];
            $payment->save();

          $request->session()->flash('alert-success', 'Payment Has Been inserted Successfully');
          return redirect('collection/payment/1');

          //dd($insertPayment); 
 }




        }

所以在我的表单中,付款相关的详细信息在一个数组中,我想知道如何创建多行?并将它们保存在一起。

谢谢&amp;此致

1 个答案:

答案 0 :(得分:4)

试试这个,

$result = Banner::create([
            'name' => $name,
            'status' => $status,
            'description' => $description,
            'category_id' => $category_id,
            'ordering' => $ordering,
            'link' => $link,
        ]);
$result = Banner::create($data);

您可以传递多维数组,在这种情况下您必须使用insert

for(..){
$data[] = [
                'name' => $name,
                'status' => $status,
                'description' => $description,
                'category_id' => $category_id,
                'ordering' => $ordering,
                'link' => $link,
            ];
}

 $result = Banner::insert($data)

注意:这不会更新/创建时间戳,因此您必须使用插入数组传递它。

希望有所帮助......