php - Laravel Eloquent 和复杂的关系

标签 php laravel laravel-4 eloquent

Laravel 似乎是一个非常不错的 PHP 框架,捆绑了一个很好的 ORM (Eloquent)。但是,laravel 文档缺少一些东西。文档中仅包含基本内容。

无论如何,当涉及 Eloquent 和模型关系时,当它跨越超过 2 个模型时,我遇到了问题。

例如,我有以下场景。

我有四个数据库表,即: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');
}

What do I want to do?:我想获取某个用户的所有包。用户属于位置,包也属于位置。因此,我想从属于用户的所有位置检索属于用户这些位置的包。 我还希望对结果集进行分页。

我尝试了以下方法:

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

关于php - Laravel Eloquent 和复杂的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386962/

相关文章:

php - 无法执行 Laravel artisan 命令

php - 在 Apache 中运行 Django 和 PHP 应用程序

php - 用碳增加秒数

laravel - 图片上传和显示问题

php - Laravel Blade - 通过@include 或@yield 传递变量

php - symfony twig 数组按键显示

php - 为什么 PHP 5.5 的 OPcache 显示为零命中? suPHP 的罪魁祸首?

php - Laravel 无法将空值插入可为空的数据库字段

javascript - 如何将 PHP 变量从 Blade 格式的 HTML 传递给 JavaScript 函数

php - 创建 Zip 和强制下载 - Laravel