使用laravel更新联结表

时间:2016-04-18 11:25:35

标签: php html mysql laravel laravel-5.2

问题很简单我有一个表格可以将数据插入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

如果需要任何其他文件/代码,请告知我们。急需帮助!谢谢!

1 个答案:

答案 0 :(得分:1)

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');