Laravel将多个输入表单插入数据库

时间:2016-12-02 04:20:03

标签: php jquery laravel

我已经创建了一个多输入表单,如下图所示,我想保存到数据库,问题是当我使用Terminate batch job (Y/N)? N 时,它只显示第二行数据。

如何将每行保存到数据库?

enter image description here

这里是我的laravel控制器

dd()

这里是我的表脚本,我使用jQuery创建它

public function store(Request $request)
{

        $input = Input::all();
        $condition = $input['service_id'];
        foreach ($condition as $key => $condition) {
            $detailorder = new DetailOrder;
            $detailorder->serivce_id = $input['service_id'][$key];
            $detailorder->order_type = $input['order_type'][$key];
            $detailorder->select_plan = $input['select_plan'][$key];
            $detailorder->qty = $input['qty'][$key];
            $detailorder->unit_price = $input['unit_price'][$key];
            //$detailorder->mandays = $input['mandays'][$key];
            $detailorder->note = $input['note'][$key];
            }
            dd($detailorder);

}

3 个答案:

答案 0 :(得分:2)

public function store(Request $request)添加如下所示的行

public function store(Request $request)
{

        $input = Input::all();
        $condition = $input['service_id'];
        foreach ($condition as $key => $condition) {
            $detailorder = new DetailOrder;
            $detailorder->serivce_id = $input['service_id'][$key];
            $detailorder->order_type = $input['order_type'][$key];
            $detailorder->select_plan = $input['select_plan'][$key];
            $detailorder->qty = $input['qty'][$key];
            $detailorder->unit_price = $input['unit_price'][$key];
            //$detailorder->mandays = $input['mandays'][$key];
            $detailorder->note = $input['note'][$key];

            //for saving each DetailOrder to database
            $detailorder->save();
            } 
}

请注意,应在save()循环内调用foreach以将每行保存到数据库。

考虑到您的JavaScript正常运行,上述修改将保存数据库中每行的数据。

答案 1 :(得分:1)

检查以下一行:

foreach ($condition as $key => $condition) {
    $detailorder = new DetailOrder;
    // here you are creating a new object on each iteration, means on each iteration new object overrides old one, that's why you are getting the last record only
}

要解决此问题,请将此对象创建代码置于循环之外,然后重试。

答案 2 :(得分:1)

您可以使用以下代码插入多个项目:

DB::table('tablename')->insert($tableitems);