Laravel看起来像一个非常好的
PHP框架,捆绑了一个很好的ORM(Eloquent).然而,laravel文档是缺乏的东西.文档中只包含基本内容.
无论如何,当涉及到超过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','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以有效的方式做到这一点?或者它是不可能的?
//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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。