我有3个模型:User
,Role
,Tool
其中每个用户可以有很多角色,每个角色可以有很多工具。Laravel ManyToMany多个
多对多的关系在每种情况下都能很好地工作。我可以访问:
User::find(1)->roles
Tool::find(1)->roles
Role::find(1)->tools
Role::find(1)->users
我的表是:
users
id
name
roles
id
name
tools
is
name
role_user
id
role_id
user_id
role_tool
id
role_id
tool_id
在每个模型:
//In User Model
public function roles()
{
return $this->belongsToMany('Rol');
}
//In Role Model
public function users()
{
return $this->belongsToMany('User');
}
public function tools()
{
return $this->belongsToMany('Tool');
}
//In Tool Model
public function roles()
{
return $this->belongsToMany('Rol');
}
我需要得到像单个用户的所有工具:User::find(1)->roles()->tools
。我怎样才能做到这一点?
但我l9ke一解决方案在一个访问数据库不是一个foreach解决方案 – CRIMUVI
@CRIMUVI我扩展了我的答案给你。 – totymedli
工作最后的解决方案,谢谢! – CRIMUVI