2016-06-09 76 views
0

我想从数据库查询中访问数据,我认为这需要一个连接。我拥有的用户可以与众多小组分开。我正在使用belongsToMany 关系。我的模型是这样的加入透视表访问数据

class User extends Model 
{ 
    protected $table = 'users'; 
    protected $guarded = []; 

    public function group() 
    { 
     return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('user_id', 'group_id'); 
    } 
} 

class Group extends Model 
{ 
    protected $table = 'user_groups'; 
    protected $guarded = []; 
    use SoftDeletes; 

    public function user() 
    { 
     return $this->belongsToMany('App\User', 'users_user_groups')->withPivot('user_id', 'group_id'); 
    } 
} 

当我运行一切我也需要,我可能会得到如下的数据。

users 
+----+---------------+ 
| id | name   | 
+----+---------------+ 
| 1 | John Doe  |  
+----+---------------+ 

user_groups 
+----+---------------+-----------------+ 
| id | name   | description  | 
+----+---------------+-----------------+ 
| 1 | Group AA  | Something  |  
+----+---------------+-----------------+ 
| 2 | Group BB  | Something  |  
+----+---------------+-----------------+ 

users_user_groups 
+----+---------------+-----------------+ 
| id | user_id  | group_id  | 
+----+---------------+-----------------+ 
| 1 | 1    | 1    |  
+----+---------------+-----------------+ 
| 2 | 1    | 2    |  
+----+---------------+-----------------+ 

所以我知道id为1的用户属于具有的1和2的id是什么,我试图做的就是抓住所有的数据库中谁 属于名为admin将USER_GROUP用户的user_groups 。所以,我想这样的事情

DB::table('users')->select('userName') 
    ->join('user_groups', 'users_user_groups') 
    ->where('name', '=', 'admin')->get(); 

这个我知道全错了,我怎么能使用belongsToMany和数据透视表时,得到一组内的所有用户?

谢谢

回答

1

Eloquent使用关系,而不是查询生成器。

你可以实现你做这样的事情瞄准什么:

$group = Group::where('name', 'admin')->first(); 
$users = $group->users; // Where users is the name of your relationship (At the moment you have user) 

引擎盖下,会做两个SQL语句和它们雄辩对象一起映射,而不是加入。该语句将是这个样子:

select * from user_groups where name = ? and deleted_at is not null limit 1 
select * from users where id in (?, ?) 

当你有一个实例Group通过调用它,仿佛它是一个属性执行的关系。因此在那之后$users将包含User实例的集合,因此您可以通过它们循环:

foreach ($users as $user) { 
    // Do something with $user 
}