问题很简单,我有一个表单,可以将数据插入 Handymen 表(除复选框之外的所有内容)和技能表(复选框)中,但是它们是使用连接表连接的,当我单击提交按钮时,数据会添加到两个表中但是,如何让它更新连接表以添加新行,并添加刚刚添加的 Skill_id 和 Handyman_id?
function addhandyman()
{
return view('layouts/addhandyman');
}
function pushdetails(Request $request)
{
$handyman = new Handyman();
$handyman->first_name = $request->first_name;
$handyman->last_name = $request->last_name;
$handyman->street = $request->street;
$handyman->postcode = $request->postcode;
$handyman->town = $request->town;
$handyman->save();
$skill = new Skill();
$skill->skill = $request->skill;
$skill->save();
return redirect('addhandyman');
}
<小时/>
@section('content')
<h1>Add new Handyman</h1>
<form action="{{url('pushdetails')}}" method="POST">
{{ csrf_field() }}
<div>
<input type='text' name='first_name' placeholder='Enter First Name' />
<input type='text' name='last_name' placeholder='Enter Last Name' />
<input type='text' name='street' placeholder='Enter your Street' />
<input type='text' name='postcode' placeholder='Enter your postcode' />
<input type='text' name='town' placeholder='Enter your town' />
<label>Carpenter</label>
<input type='checkbox' name='skill' value='Carpenter' />
<label>Plumber</label>
<input type='checkbox' name='skill' value='Plumber' />
<label>Painter</label>
<input type='checkbox' name='skill' value='Painter' />
</div>
<input type="submit" name="submitBtn" value="Add new Handyman">
</form>
@endsection
如果需要任何其他文件/代码,请告诉我。非常需要帮助!谢谢!
最佳答案
Laravel Models (Eloquent) 的一个很酷的事情是,当您创建新的资源/模型时,它实际上会将新创建的主键 ID 从数据库中的新资源提取到您的模型中。
所以当你这样做时:
$model = new Model();
$model->field = "value";
$model->save();
// This will actually already have the Primary Key ID in it.
$mID = $model->id;
因此,手动方法是从模型中提取单独的 ID,然后手动将它们添加到表中。或者您可以使用 Eloquent's Relationships Builder 在模型中设置关系.
所以它看起来像这样:
$h_id = $handyman->id;
$s_id = $skill->id;
DB::table('myJunctionTable')->insert(array('h_id' => $h_id, 's_id' => $s_id));
添加代码后:
$handyman->first_name = $request->first_name;
$handyman->last_name = $request->last_name;
$handyman->street = $request->street;
$handyman->postcode = $request->postcode;
$handyman->town = $request->town;
$handyman->save();
$skill = new Skill();
$skill->skill = $request->skill;
$skill->save();
$h_id = $handyman->id;
$s_id = $skill->id;
DB::table('myJunctionTable')->insert(array('h_id' => $h_id, 's_id' => $s_id));
return redirect('addhandyman');
关于php - 使用 laravel 更新联结表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36692619/