问题描述
我有一个简单的数据库设置:用户,组,页面-每个都有很多.参见图: http://i.imgur.com/oFVsniH.png
I have a simple database setup: Users, Groups, Pages - each are many to many.See diagram: http://i.imgur.com/oFVsniH.png
现在,我有一个可变的用户ID($ id),并希望以此返回用户可以访问的页面的列表,这显然是因为在所有表上都是多对多的.
Now I have a variable user id ($id), and with this I want to get back a list of the pages the user has access to, distinctly, since it's many-to-many on all tables.
我已经像这样设置了我的主要模型:
I've setup my main models like so:
class User extends Eloquent {
protected $table = 'ssms_users';
public function groups()
{
return $this->belongsToMany('Group', 'ssms_groups_users', 'user_id','group_id');
}
}
class Group extends Eloquent {
protected $table = 'ssms_groups';
public function users()
{
return $this->belongsToMany('User', 'ssms_groups_users', 'user_id','group_id');
}
public function pages()
{
return $this->belongsToMany('Page', 'ssms_groups_pages', 'group_id','page_id');
}
}
class Page extends Eloquent {
protected $table = 'ssms_pages';
public function groups()
{
return $this->belongsToMany('Group', 'ssms_groups_pages', 'group_id','page_id');
}
}
只需执行以下操作即可获取用户所属的组:
I can get the groups the user belongs to by simply doing:
User::with('groups')->first(); // just the first user for now
但是我完全迷失了如何通过一个查询获得用户(清晰地)访问的页面?
However I'm totally lost on how to get the pages the user has access to (distinctly) with one query?
我相信SQL将会是这样的:
I believe the SQL would be something like:
select DISTINCT GP.page_id
from GroupUser GU
join GroupPage GP on GU.group_id = GP.group_id
where GU.user_id = $id
任何人都可以帮忙吗?
谢谢
推荐答案
您之前是否尝试过这种方法?
Have you tried something like this before?
$pages = User::with(array('groups', 'groups.pages'))->get();
快速加载可能是解决您问题的方法:快速加载
Eager loading might be the solution to your problem: eager loading
这篇关于“三路"使用口才的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!