使用laravel更新连接表


Updating junction table using laravel

问题很简单我有一个表单,它将数据插入Handymen表(复选框除外)和Skill表(复选盒),但它们使用连接表连接,当我单击提交按钮时,数据会添加到这两个表中,但我如何更新连接表以添加新行,并添加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的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');