如何在Laravel的数据透视表中向其他列添加数据

Nit*_*mar 3 laravel eloquent laravel-5.3

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

我的Users模特:

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

我的Plan模特:

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

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

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

帮我解决这个问题。

Ale*_*nin 6

您应该这样使用attach()

$user->relations()->attach($plan_id, ['child' => $childid]);
Run Code Online (Sandbox Code Playgroud)