【发布时间】:2022-03-04 04:47:48
【问题描述】:
我在 Laravel 工作了几天后遇到了一个问题。
我的数据库如附图。database
用户角色多对多关系正常工作。
此外,我想在 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);
}
当我填充表格时,我可以获得数据:关系工作。
现在我想保存数据并让 Laravel 自动填充表格。此时此刻,我将角色数据保存在 users.php 中:
$this->Roles()->sync($roles);
($roles 是来自表单请求的 json 数组数据..)。
数据透视表获取 user_id 和 role_id。好的,很酷。
现在,当我添加角色时,我应该写什么来在 role_user 数据透视表中获取 role_user_id 和 tag_id?
提前谢谢你!
【问题讨论】:
-
我试过了:$this->role_users()->tags()->sync($someData);但出现错误“调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::tags()”
标签: php laravel controller many-to-many