【问题标题】:How to create a row for user in another related table when the user is created in laravel?在laravel中创建用户时,如何在另一个相关表中为用户创建一行?
【发布时间】:2016-10-08 16:56:32
【问题描述】:

我需要在相关表中创建一行。这是一个 hasOne 和 belongsTo 关系。 用户拥有一个个人资料 个人资料属于用户

我想在创建用户后创建个人资料行。

public function store(UserRequest $request)
{
    $user= new User();
    User::create($request->all());
    Profile::create([
        'user_id' => $user->user_id,
    ]);
    return redirect()->route('users.index')
}

【问题讨论】:

    标签: sql laravel


    【解决方案1】:

    当用户在项目的任何位置创建时,您可以在 laravel 中使用事件(观察者)来完成您的工作。

    https://laravel.com/docs/5.3/eloquent#observers

    【讨论】:

      【解决方案2】:

      使用Model Observers

      您可以为created 事件声明一个观察者,并在那里创建配置文件。

      public function creating($model)
      {
          // Create your related profile.
          // Note that profile relationship must be defined at your model class
          $model->profile()->create();
      
          return true;
      }
      

      这个观察者可以在模型观察者类上创建,也可以在模型启动时声明。

      【讨论】:

        【解决方案3】:

        试试这样:

        public function store(UserRequest $request)
        {
            $user = User::create($request->all());
            $user->profile()->create([]);
        
            return redirect()->route('users.index')
        }
        

        你必须在用户类中有hasOne关系方法:

        public function profile()
        {
            return $this->hasOne(Profile::class);
        }
        

        此更新不起作用;有解决办法吗

        public function update(Request $request, $id)
        {
            $input = $request->all();
            $employee = Employee::findorfail($id);
            $update = $employee->update($input);
            $employee->personaldetail()->update(['employee_id' => $employee->employees_id,]);
            return redirect()->route('employees.index')->with('message','Employee has been updated');
        }
        

        【讨论】:

        • 更新它的方法是什么。我尝试用更新替换创建?
        • 我正在为更新而苦苦挣扎。我在上面添加的更新代码是在db中将关系employee_id重置为NULL。
        猜你喜欢
        • 1970-01-01
        • 2015-04-12
        • 2018-02-12
        • 2012-07-09
        • 2018-05-27
        • 2023-04-04
        • 2019-04-14
        • 2016-01-20
        • 1970-01-01
        相关资源
        最近更新 更多