如何在laravel 5.4中插入数组数据

时间:2018-04-07 05:55:34

标签: laravel

我有产品表设备表 我加入了这两个表格,我选择了device.id& product.name,现在我想使用device将此数据插入到现有的device.id表中。
我想在我的数据库中插入多个下拉列表值。谁能告诉我怎样才能解决这个问题?以下是我的Controller代码 -

foreach ($request->all() as $value)
        {
$deviceById= Device::find($request->id);
            if($request->destination_type == 'dealer')
            {
                $deviceById->destination_location=$value->dealer_id;
            }else
            {
                $deviceById->destination_location=$value->office_id;
            }
            $deviceById->save();
        }
        flash('Device Dispatch added successfully!')->success()->important();
        return redirect()->back();

2 个答案:

答案 0 :(得分:0)

您可以创建所有下拉列值的数组并转换为json字符串并将其存储在数据库中

你可以这样做。根据您的要求改变。它只是一个逻辑演示。



$deviceById= Device::find($request->id);
$destination = array();

foreach ($request->all() as $value)
{
    if($request->destination_type == 'dealer')
    {
        $destination[] = $value->dealer_id;
    }else
    {
        $destination[] = $value->office_id;
    }

}
$jsonString = json_encode($destination);

$deviceById->destination_location = $jsonString
$deviceById->save();

flash('Device Dispatch added successfully!')->success()->important();
return redirect()->back();




答案 1 :(得分:0)

我这样解决。我使用了Elequent ORM

            if($request->destination_type == 'Dealer')
            {
                DB::table('devices')
                    ->whereIn('id',$request->device_list)
                    ->update(['dealer_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
                flash('Device Dispatch dealer added successfully!')->success()->important();
            }else
            {
                DB::table('devices')
                    ->whereIn('id',$request->device_list)
                    ->update(['office_id'=>$request->destination_location,'device_status'=>"Dispatch"]);
                flash('Device Dispatch office added successfully!')->success()->important();
            }