2013-10-15 92 views
8

Laravel看起來像一個非常漂亮的PHP框架,捆綁了一個好的ORM(Eloquent)。然而,laravel文檔是缺乏的。只有基本的東西出現在文檔中。Laravel雄辯和複雜的關係

無論如何,當涉及超過2個模型的雄辯和模型關係時,我有一個問題。

例如,我有以下情況。

我有即4個數據庫表:userslocationsusers_locationspackages。 和模型/表之間的關係如下:

用戶可以屬於多個位置,反之亦然。 一個位置可以有很多包。

而我相應的模型關係如下:

//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; 

問題是,上述,我不能在包實現分頁。有誰知道如何正確使用口頭禪並以有效的方式做到這一點?或者它是不可能的?

回答

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

可以用'paginate($ page_size)'代替。有沒有一個能夠獲得上述結果的雄辯線條代碼? – WebNovice

+0

感謝關於paginate()的提示 - 我完全忘了它。至於雄辯,我不認爲你可以用一次滑動來做到這一點,雖然在將來看到它會非常優雅。最後,您可以隨時使用Fluent並根據需要加入表格。 –