Php 拉维尔雄辩而复杂的关系
Laravel似乎是一个非常好的PHP框架,与一个好的ORM(雄辩)捆绑在一起。然而,laravel文档中缺少一些内容。文档中只有基本的内容 无论如何,当涉及到雄辩和模型关系时,当它跨越两个以上的模型时,我有一个问题 例如,我有以下场景。 我有四个数据库表,即:Php 拉维尔雄辩而复杂的关系,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,Laravel似乎是一个非常好的PHP框架,与一个好的ORM(雄辩)捆绑在一起。然而,laravel文档中缺少一些内容。文档中只有基本的内容 无论如何,当涉及到雄辩和模型关系时,当它跨越两个以上的模型时,我有一个问题 例如,我有以下场景。 我有四个数据库表,即:users,locations,users\u locations,packages。 模型/表格之间的关系如下所示: //User Model: public function locations(){ return $this
users
,locations
,users\u 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');
}
用户可以属于多个位置,反之亦然。
一个位置可以有许多包
我对应的模型关系如下:
//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;
问题是,由于上述原因,我无法在包上实现分页。有人知道如何使用雄辩的语言以有效的方式正确地完成吗?还是不可能?可以做
分页($page\u size)
。有没有一行代码可以雄辩地得到上面的结果?谢谢关于paginate()的提示-我完全忘记了。至于雄辩,我不认为你能做到这一点与一刷尚未,虽然它将是非常优雅的看到,在未来。最后,您可以随时使用Fluent并根据需要加入表。
//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;