我有两个表用户和锦标赛。我已经为多对多定义了模型中的关系。我有第三个数据透视表,其中存储了注册锦标赛的用户。在这个表中,我也想存储用户的用户名。这是我的存储功能
$tournament->users()->syncWithoutDetaching([auth()->id()]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);
我可以添加什么以便我也可以存储用户名?提前致谢
在数据透视表中存储用户名只需在数据透视表中创建一个额外的列user_name
,您可以像下面这样保存它
$userId = auth()->id();
$userName =auth()->user()->name;
$tournament->users()
->syncWithoutDetaching([$userId=>['user_name'=>$userName]]);
$request->session()->flash('success', 'You have joined the tournament');
return back()->with('tournament', $tournament);
在调用关系时也获取用户名添加withPivot()
到您的模型
public function relationName(){
return $this->belongsToMany(Model::class)->withPivot('user_name');
}
更新
$userName = auth()->user()->name ; // Instead name get the value you want from table column name
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句