在laravel中,我想将一种形式的数据插入到两个表中。
我的表格是:
<input type="text" name="name"class="form-control">
<input type="text" name="age"class="form-control">
<input type="text" name="sex"class="form-control">
<input type="text" name="location"class="form-control">
Run Code Online (Sandbox Code Playgroud)
我想插入name,age和sex表details。并输入location到表locations
location模型belongsTo detail模型。
如何同时插入它们?以及如何自动匹配idofdetail与detail_idof location?
我有搜索,但太难了。我希望有一种简单的方法可以遵循。
到目前为止,您还没有向我们展示您的模型关系以及控制器中的内容。但是假设您的模型正确相关并且您的表字段名称与表单名称相同,您可以在控制器中尝试以下操作:
public function store(Request $request)
{
$detail = new detail();
$detail->name = $request->input("name");
$detail->age = $request->input("age");
$detail->sex = $request->input("sex");
$detail->save();
$location = new location();
$location->detail_id = $detail->id;
$location->location = $request->input("location");
$location->save();
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。
| 归档时间: |
|
| 查看次数: |
4603 次 |
| 最近记录: |