如何将数据添加到 laravel 中数据透视表 table 中的附加列

How to add data to additional column in pivot table in laravel

我正在尝试在 Laravel 5.3 中构建应用程序,我想在数据透视 table 中添加额外的列数据。以下是我的代码:

我的Users模特:

public function relations()
{
  return $this->belongsToMany('App\Plan')->withPivot('child');
}

我的Plan模特:

public function relations()
{
  return $this->belongsToMany('App\User')->withPivot('child');
}

在我的控制器中,我正在从 Auth::user(); 获取用户数据,对于计划和子元素,我正在通过请求获取。我想将其存储到我的数据透视表 table。以下是我在控制器中尝试的代码:

$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);

帮我解决这个问题。

尝试 save 方法:

$user->relations()->save($plan, ['child' => $childid]);

Docs

你应该这样使用attach()

$user->relations()->attach($plan_id, ['child' => $childid]);

saveattach 都有效。当我尝试使用 tinker

时,attach 将 return null 而 save 将 return $user 对象