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
How to add data to additional column in pivot table in laravel
提问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 Users
model:
我的Users
型号:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan
model:
我的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
回答by Amit Gupta
回答by Ryan
Both save
and attach
work. Just that attach
will return null while save
will return $user object when I try with tinker
无论save
和attach
工作。当我尝试使用 tinker 时,这attach
将返回 null 而save
将返回 $user 对象