2016-06-09 1 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 사용자가 내가 는 admin 이름을 가진 user_group에 속하는 내 데이터베이스 내의 모든 사용자를 잡아하면됩니다하려고 무엇 1과 2의 ID와 user_groups에 속하는 알고 . 그래서 belongsToMany 및 피벗 테이블을 사용할 때이 그룹 내 모든 사용자가 얻을 수있는 방법, 내가 아는이 모든 잘못이

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

같은 것을 시도하고있다?

감사

답변

1

설득력이 관계가 아닌 쿼리 빌더를 사용합니다.

당신은 이런 식으로 뭔가를 수행하여 목표로하고 무엇을 달성 할 수있는 두 개의 SQL 문을 오히려 조인보다 설득력 객체에 함께 매핑합니다 후드에서

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

. 당신은 당신이 재산 인 것처럼 그것을 호출하여 관계를 실행 인스턴스 Group이있을 때

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

: 명령문은 다음과 같이 보일 것입니다. 따라서 $users에는 User 인스턴스의 콜렉션이 포함되어 있으므로 루프 할 수 있습니다.