我在Laravel中实现了bootstrap multi select list,我有一个查询要将所选项插入数据库,但我的查询只插入最低id
个数字的项目。因此,如果我选择ID为2
3
4
的员工,则会始终插入ID 2
,其余部分将被忽略。
想象一下我的网络应用程序将要做什么:我有一个汽车维修,每个维修都有自己的id
。在创建新修复时,我首先创建修复实例,然后我得到它id
并将其插入到表repair_employees
中,其中包含以下列:" worker_id" " repair_id"
所以,让我说我用id = 87
进行了新的修复。
我从多选列表中选择ID为2
,3
,4
的工作人员。
因此,通过正确的sql插入,表格看起来像这样:
"repair_id" , "worker_id"
"87" , "2"
"87" , "3"
"87" , "4"
以下是我的插入代码:
public function addRepairWorker(Request $request , Vehicle $vehicle, $idcko){
$workers_needed = null;
DB::transaction(function () use ($request, $vehicle, $idcko) {
Log::info('Creating new repair worker instance.');
$workers_needed = new Repair_worker();
$workers_needed->repair_id = $idcko;
$workers_needed->worker_id = $request->worker_id;
DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)',
[$workers_needed->repair_id, $workers_needed->worker_id]);
Log::info('Repair created.');
flash('Repair successfully added.', 'success');
});
}
这里(如果需要)是我对多选列表的看法(form.blade.php):
<select multiple class="form-control" name="worker_id">
@foreach($workers as $worker)
<option value="{{ $worker->id }}"
@if(isset($repair_worker) &&
($worker->id == $worker_id))
selected @endif)>
{{ $worker->name }} {{$worker->surname}}
</option>
@endforeach
</select>
我需要更改以插入所有&#34;工人&#34; ?
修改
这是我的控制器中的函数,我在哪里有一个循环来获取所有数组值?它有点令人困惑,哪个部分应该循环来完成它。
public function addRepair(Request $request, Customer $customer, Vehicle $vehicle)
{
$workers = DB::select(DB::raw('select workers.id as id, workers.name as name, workers.surname as surname from workers order by name'));
if ($request->isMethod('post')) {
$this->validate($request, [
'worker_id' => 'required'
//'part_id' => 'required'
]);
$this->repairsService->createRepair($request, $vehicle);
foreach ($workers_id as $id){
$this->repairsService->addRepairWorker($request, $vehicle); //this function does the insert into database
}
return redirect()->route('Customers:detailVehicle', ['customer' => $customer, 'vehicle' => $vehicle]);
}
return view('repairs.form', ['repair' => null, 'workers' => $workers]);
}
答案 0 :(得分:0)
首先,在HTML中选择,您需要调整名称(注意方括号)。这将在您的请求中创建一个数组输入值。如果不这样做,您将只有一个值,因为它将覆盖所有以前的值。
<select multiple class="form-control" name="worker_id[]">
在你的控制器中,你需要循环遍历 $ worker_id 数组并为每个值执行插入。
另外,只需:
$workers_needed->save();
而不是你的插入语句,因为你正在打败首先拥有模型的目的。