2013-10-15 3 views
8

Laravel은 훌륭한 ORM (Eloquent)과 함께 번들 된 아주 멋진 PHP 프레임 워크처럼 보입니다. 그러나 laravel 문서는 부족한 부분입니다. 문서에는 기본적인 내용 만 있습니다.Laravel Eloquent and complex relationships

어쨌든 2 개 이상의 모델에 걸쳐 있으면 Eloquent와 모델 관계에 관한 문제가 있습니다.

예를 들어 다음과 같은 시나리오가 있습니다. users, locations, users_locations, packages :

나는, 즉 네 개의 데이터베이스 테이블을 가지고있다. 그리고 모델/테이블 간의 관계는 다음과 같습니다 :

사용자는 많은 위치에 속할 수 있으며 그 반대의 경우도 마찬가지입니다. 위치는 많은 패키지를 가질 수 있습니다.

//User Model: 
public function locations(){ 
    return $this->belongsToMany('Location', 'users_locations', 'user_id', 'location_id'); 
} 

//Location Model: 
public function users(){ 
    return $this->belongsToMany('User', 'users_locations', 'location_id', 'user_id'); 
} 
public function packages(){ 
    return $this->hasMany('Package', 'location_id'); 
} 

//Package Model: 
public function location(){ 
    return $this->belongsTo('Location', 'location_id'); 
} 

내가 뭘하고 싶어 다음과 같이

그리고 내 해당 모델의 관계는? : 모든 패키지가 사용자에게 속하게하고 싶습니다. 사용자가 위치에 속하고 패키지가 위치에도 속합니다. 따라서 사용자에게 속한 모든 위치에서 사용자의 해당 위치에 속한 패키지를 검색하려고합니다. 또한 결과 세트의 페이지 매김을 원합니다.

//get the logged in user ID 
$userId = Auth::user()->id 
//first get all the locations of the user 
$locations= User::with('locations')->find($userId)->locations; 
//declare an empty array to store the packages 
$packages = array(); 
//now loop through the locations 
foreach($locations as $location){ 
    //since each location can have many packages, we also have to loop through the packages 
    foreach($location->packages as $package){ 
     //store the plan in the array 
     $packages[] = $package; 
    } 
} 
//ok now we got the list of packages 
return $packages; 

문제는, 위의에, 나는 패키지에 페이지 매김을 구현할 수 없습니다 :

나는 다음과 같은 노력했다. 누구든지 제대로하고 효율적으로 Eloquent를 사용하여이를 수행하는 방법을 알고 있습니까? 아니면 그냥 불가능한가요?

답변

5
//get the logged in user ID 
$userId = Auth::user()->id 
//first get all the locations of the user 
$locations= User::with('locations')->find($userId)->locations; 


/* perhaps you can alternatively use lists() function to get the ids 
something like: $loc_ids = DB::table('locations')->where('user_id',$userId)->lists('id'); */ 
$loc_ids = array(); 
foreach($locations as $location) 
{ 
    $loc_ids[] = $location->id; 
} 

$packages = Package::whereIn('location_id', $loc_ids)->skip($offset)->take($page_size)->get(); 

return $packages; 
+1

대신 '페이지 매김 ($ page_size)'을 수행 할 수 있습니다. 위의 결과를 얻을 수있는 곳에 설득력있는 라인 코드 하나가 있습니까? – WebNovice

+0

paginate()에 대한 팁을 보내 주셔서 감사합니다 - 나는 그것에 대해 완전히 잊어 버렸습니다. Eloquent에 관해서는 비록 당신이 아직 한 번 스 와이프로 그것을 할 수 있다고는 생각하지 않지만, 미래에 볼 때 매우 우아 할지라도. 결국 Fluent를 사용하고 원하는대로 테이블에 가입 할 수 있습니다. –