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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40949818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:51:57  来源:igfitidea点击:

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

laraveleloquentlaravel-5.3

提问by Nitish Kumar

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:

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

My Usersmodel:

我的Users型号:

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

My Planmodel:

我的Plan型号:

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

In my controller I'm fetching the user data from Auth::user();and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:

在我的控制器中,我从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]);

Help me out in this.

帮我解决这个问题。

回答by Alexey Mezenin

You should use attach()like this:

你应该这样使用attach()

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

回答by Amit Gupta

Try the savemethod as:

尝试以下save方法:

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

Docs

文档

回答by Ryan

Both saveand attachwork. Just that attachwill return null while savewill return $user object when I try with tinker

无论saveattach工作。当我尝试使用 tinker 时,这attach将返回 null 而save将返回 $user 对象