简体   繁体   English

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

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

i try to update value of name in table student and auto updated in column name at table users我尝试更新表学生中的名称值并自动更新表用户中的列名

my controller code is我的 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);
   }

no errors but it change another user's name at table users.没有错误,但它在表用户处更改了另一个用户的名称。

You can try with mutators :您可以尝试使用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;
    }
}

You should use the observers.你应该使用观察者。 When a User is updated, the Student will automatically also being updated.更新用户时,学生也将自动更新。

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

相关问题 如何在laravel中通过另一个表列更新自动更新一个表列 - how to automatically update one table column by another table column update in laravel 根据Laravel中另一列(同表)的值自动更新列(7) - Update column automatically based on value of another column (same table) in Laravel (7) 如何使用特定的列值更新laravel中的表 - How to update a table in laravel with a specific column value 如何根据 Laravel 8 中同一表中的另一列在列中存储值 - How to store value in column depending on another column in same table in Laravel 8 如何将每列中的 2 个值输入到另一个表中的一列 - how to input 2 value from each column to one column in another table 表格中的栏值未更新 - Column value not updated in the table Laravel 8 - 如何将一个表中的值更新到另一个表中 - Laravel 8 - How to update the value in one table to another table 如何访问与另一表相关的一列Laravel 5.1 - How to access one column related to another table Laravel 5.1 创建迁移 Laravel 后如何更新特定的列表值? - How to update specific column table value after create migrations Laravel? 如何在一行中获取具有相同 id 但在另一列中具有不同值的数据并在 php 中的表中显示一个月 - How to fetch data with same id in a row but different value in another column and display one month into table in php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM