8
Laravel看起来像一个非常漂亮的PHP框架,捆绑了一个好的ORM(Eloquent)。然而,laravel文档是缺乏的。只有基本的东西出现在文档中。Laravel雄辩和复杂的关系
无论如何,当涉及超过2个模型的雄辩和模型关系时,我有一个问题。
例如,我有以下情况。
我有即4个数据库表: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;
的问题是,上述,我不能在包实现分页。有谁知道如何正确使用口头禅并以有效的方式做到这一点?或者它是不可能的?
可以用'paginate($ page_size)'代替。有没有一个能够获得上述结果的雄辩线条代码? – WebNovice
感谢关于paginate()的提示 - 我完全忘了它。至于雄辩,我不认为你可以用一次滑动来做到这一点,虽然在将来看到它会非常优雅。最后,您可以随时使用Fluent并根据需要加入表格。 –