Laravel如何更新另一个表中另一列的值?

时间:2020-05-28 09:43:25

标签: laravel eloquent laravel-7

我有两个名为“用户”和“请求”的表。在请求表中,我想将用户emp_status更新为“管理员”,同时也将表“用户”更新为

这是我的控制者:

public function update(Request $request, $id)
{
    $status = "Admin";

    $admin = DB::table('users')
            ->where('emp_no', $id)
            ->update(array('emp_status'=>$status));

    $forms = Requests::find($id);
    $forms->emp_no = $request->get('emp_no');
    $forms->emp_name = $request->get('emp_name');
    $forms->email = $request->get('email');
    $forms->department = $request->get('department');
    $forms->emp_status = $request->get('emp_status', $admin);
    $forms->justification = $request->get('justification');

    $forms->save();

    return redirect('admins.request')->with('Success','Employee has been changed to admin!');
}

请求模型:

class Requests extends Model
{
    protected $fillable = [     
        'emp_no','emp_name','email','emp_status','department','justification'
    ];

   public function User(){
        return $this->hasMany('App\Requests');
   }
}

用户模型:

protected $fillable = [
    'emp_no', 'emp_name', 'emp_contact','gender','email','password'
];

public function Requests(){
    return $this->hasOne('App\Requests');
}

当我在表单中选择“管理员”选项并单击“批准”时,它应根据emp_no同时更新两个表。这是屏幕截图。 The Form Details blade file

我应该怎么做?

1 个答案:

答案 0 :(得分:0)

假设您的刀片文件中的<select>定义如下:

<select id="status" name="status">
<option value="Admin">Admin</option>
<option value="Normal">Normal</option>
</select>

然后在您的控制器中使用此$request->status

对其进行调用

但是,由于您同时更新两个表,因此您应该使用transaction范围来包围更新方法的内部,这样,如果在此过程中发生任何错误,它将回滚

DB::transaction(function () use ($id, $request){


    $admin = DB::table('users')
        ->where('emp_no', $id)
        ->update(array('emp_status'=>$request->status));

    $forms = Requests::find($id);
    $forms->emp_no = $request->get('emp_no');
    $forms->emp_name = $request->get('emp_name');
    $forms->email = $request->get('email');
    $forms->department = $request->get('department');
    $forms->emp_status = $request->get('status');
    $forms->justification = $request->get('justification');

    $forms->save();
});