Laravel 5,按关系计数分页和排序列表

时间:2015-04-05 14:25:33

标签: php pagination laravel-5

我试图按链接表计数对查询进行排序,但无法弄清楚如何使用Laravel分页;下面是我传递给视图的查询

我认为Laravel 5 paginator方法已被移动了吗?

    $companies = Company::with('locations')->get()->sortBy(function($count)
    {
        return $count->locations->where('status', '=', 'Active')->count();
    }, null, true);

因为调用了get和sortby函数,所以我无法应用分页(下面的错误)

  

调用未定义的方法Illuminate \ Database \ Eloquent \ Collection :: pagination()

也许有另一种方法可以通过hasMany关系的计数进行排序 - 在这种情况下" locations"。 (附带问题;我不知道如何使用hasManyThrough关系进行上述工作)。

模型关系如下所示

public function locations()
{
    return $this->hasMany('App\Location');
}

public function equipment()
{
    return $this->hasManyThrough('App\Equipment', 'App\Location');
}

使用类似下面的内容会给出一个未定义的" make"方法

return Paginator::make($companies->all(), $companies->getTotal(), $companies->getPerPage())

1 个答案:

答案 0 :(得分:1)

以下是我编辑的答案,排序依据命令和分页确实可以一起工作,以下内容对您有用,当然您可能需要调整范围连接语句中的列。

将此功能添加到您的公司类。

    public function scopeLocationCount($query){
    return $query->join('locations','locations.company_id','=','companies.id')
            ->selectRaw('companies.*, count(locations.id) as count')->where('locations.status','=','active')->groupBy('companies.id');
}

然后你可以像这样调用paginate方法。

$companies= (Company::with('locations')->locationCount()->orderBy('count')->paginate(30));

然后在编写foreach循环后,显示需要渲染分页器的详细信息,如{!! $companies->render() !!}

希望这有帮助。