繁体   English   中英

如何更新一列中的值并自动更新不同表中的另一列 laravel

[英]how to update value in one column and automaticaly updated another column at different table laravel

我尝试更新表学生中的名称值并自动更新表用户中的列名

我的 controller 代码是

public function update(Request $request, $id)
    { 
        $user = User::where('id', $id)->first();
        $user->name = $request->name;
        $user->save();

        $student= Student::where('id', $id)->first();
        $student->name = $request->name;
        $student->save();

       return redirect()->route('profilestudent.edit', Auth::user()->student->id);
   }

没有错误,但它在表用户处更改了另一个用户的名称。

您可以尝试使用mutators

class User extends Model
{
    public function setNameAttribute($value)
    {
        $student= Student::where('user_id', $this->id)->first() if id is not key in Student
        $student->name = $value;
        $student->save();
        $this->attributes['first_name'] = $value;
    }
}

你应该使用观察者。 更新用户时,学生也将自动更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM