Laravel 多对多对多同步
几天来我在 Laravel 中遇到了一个问题。
我的数据库就像附图。数据库
用户<->角色多对多-关系正常运行。
此外,我想在 role_user 数据透视表中添加另一个多对多关系。所以我这样做了:
user.php:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function role_users()
{
return $this->hasMany(RoleUser::class);
}
role.php:
public function users()
{
return $this->belongsToMany(User::class);
}
public function role_users()
{
return $this->hasMany(RoleUser::class);
}
并透视 roleUser.php:
public function user()
{
return $this->belongsTo(User::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
当我填充表格时,我可以获得 data: 关系工作。
现在我想保存数据并让 Laravel 自动填充表。此时此刻,我将角色数据保存在 users.php 中:
$this->Roles()->sync($roles);
($roles 是来自表单请求的 json 数组数据..)。
数据透视表获取user_id和role_id。好吧,酷。
现在,当我添加角色时,我应该写什么来获取 role_user 数据透视表中的 role_user_id 和 tag_id?
提前谢谢您!
I've got a problem since several days in Laravel.
My database is like attached picture.database
User<->Role many-to-many-relationship works correctly.
In addition, I would like to add another many-to-many relationship in role_user pivot table. So I did:
user.php:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function role_users()
{
return $this->hasMany(RoleUser::class);
}
role.php:
public function users()
{
return $this->belongsToMany(User::class);
}
public function role_users()
{
return $this->hasMany(RoleUser::class);
}
And pivot roleUser.php:
public function user()
{
return $this->belongsTo(User::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
When I populate tables, I can get data: relations work.
Now I want to save data and let Laravel to populate tables automatically. At this moment and time, I save roles data in users.php with:
$this->Roles()->sync($roles);
($roles is an json array data from a form request..).
Pivot table get the user_id and role_id. Ok, cool.
Now, what should I write to get role_user_id and tag_id in role_user pivot table when I add a roles?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你应该使用
而不是
因为如果我没记错的话,同步将删除数据透视表数据。您应该将primary_key和foreign_key传递给您的belongsToMany函数。如果您想将数据添加到数据透视表中的数据透视列,请尝试添加
->withPivot('column name');
I think you should use
Rather than
Because if I'm not wrong, sync will remove the pivot data. And you should pass the primary_key and foreign_key to your belongsToMany function. If you wanted to add data to the pivot column in your pivot table, try to add
->withPivot('column name');