如何使用laravel中的键值从另一个表更新一些记录表

我有这样的表用户


| 身份证 | 用户 | 车辆_ID | 车辆_Desc |

-----------------------------------------

| 1 | 约翰 | 201 | 汽车 |

| 2 | 克里斯 | 202 | 汽车 |

我有这样的桌车


| 身份证 | 车辆 |

---------------------

| 201 | 汽车 |

| 202 | 摩托车 |

如何根据表车辆中的基准更新 Cris 记录上的 Vehicle_Desc?使用 Laravel


眼眸繁星
浏览 156回答 2
2回答

弑天下

这是一个简单的 SQL 查询,但在原始 SQL 中执行比通过内置查询构建器更容易:$userId = 2; // id of chris$sql = <<<SQL&nbsp; &nbsp; UPDATE u&nbsp; &nbsp; SET u.vehicle_desc = v.vehicle&nbsp; &nbsp; FROM users u&nbsp; &nbsp; &nbsp; &nbsp; INNER JOIN vehicles v ON v.id = u.vehicle_id&nbsp; &nbsp; WHERE u.id = ?SQL;\DB::statement($sql, [$userId]);

狐的传说

如果您想在最终用户从前端更新车辆表后立即更改用户,那么我建议您在使用分配给 Model Vehicle 的控制器时,例如 VehicleController,创建一个更新函数。假设您在 Vehicle 表中只有一个名为 Vehicle 的列。&nbsp;//Inside Vehicle Controlleruse App\User;&nbsp; &nbsp; &nbsp; &nbsp;\\call the User modeluse App\Vehicle;&nbsp; &nbsp; &nbsp;\\call the Vehicle model假设用户从表单更新了 ID 为 202 的车辆,然后在视图中创建一个表单并在其中发布带有 202 值的 ID,例如:<form method="post" action="{{ url('vehicle/'.$id) }}" >@csrf&nbsp;your form inputs and submit button</form>然后使用路由将表单发布到 VehicleController@update (或者您可以使用资源控制器)例如 Route::post('vehicle/{id}','VehicleController@update'); 然后在 Vehicle Controller 中public function update(Request $request, $id)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$request->validate([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //provide your validation here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$vehicle_req = $request['name_of_input field'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//After validation&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $vehicle = Vehicle::find($id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user = User::find($id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $vehicle->update([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Vehicle' => $vehicle_req,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user->update([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'vehicle_Desc' => $vehicle_req,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return redirect()->back()->with('success', 'Value Edited&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; successfully.');&nbsp; &nbsp; &nbsp; &nbsp; }最后,您可以在视图上显示成功消息。它将同时更新 Vehicle 表的 Vehicle Column 和 User 表的 Vehicle_Desc 。
打开App,查看更多内容
随时随地看视频慕课网APP