我正在尝试对模型结果进行分页,但我收到“分页方法不存在”。这是我的代码:
$user_dispatches = Dispatch::all()->where('user_id', Auth::id())->paginate(10);
我需要获取用户 ID 等于当前经过身份验证的用户 ID 的所有记录。无需 paginate() 方法即可正常工作。
扩展一点阿列克谢的完美答案:
=> 返回Dispatch::all()
Collection
=> 返回Dispatch::all()->where()
Collection
=> 返回Dispatch::where()
Query
=> 返回Dispatch::where()->get()
Collection
=> 返回Dispatch::where()->get()->where()
Collection
您只能在
paginate
上调用“Query
”,而不能在 Collection
上调用。
是的,对于
where
和 Queries
都有一个 Collections
函数,工作得和它们一样接近,这是完全令人困惑的,但它就是这样。
您需要删除
all()
:
Dispatch::where('user_id', Auth::id())->paginate(10);
当您使用
all()
时,您会从表中获取所有行并获得一个集合。然后您使用集合方法 where()
(而不是查询生成器方法 where()
),然后尝试在集合上使用 paginate()
方法,但它不存在。
要使用所有记录和分页,您需要使用以下代码:
$user_dispatches = Disspath::paginate(25);
您需要删除方法
all()
:
$user_dispatches = Dispatch::where('user_id', Auth::id())->paginate(10);
因为
all()
返回 Collection
而 paginate()
使用 Builder
方法
toQuery()
改变一个集合来查询:
$pacientes = Paciente::get()->toQuery()->paginate(20);
Dispatch::where('user_id', auth()->user()->id)->paginate(10);
您可以创建自己的自定义类:
<?php
namespace App\CustomClasses;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class ColectionPaginate
{
public static function paginate(Collection $results, $pageSize)
{
$page = Paginator::resolveCurrentPage('page');
$total = $results->count();
return self::paginator($results->forPage($page, $pageSize), $total, $pageSize, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected static function paginator($items, $total, $perPage, $currentPage, $options)
{
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
然后使用它:
use App\CustomClasses\ColectionPaginate;
...
$result = $query->limit(100)->get();
$paginatedResult = ColectionPaginate::paginate($result, 10);
**已解决
澄清上面的解决方案
改变...
$user_dispatches = Dispatch::all()->where('user_id', Auth::id())->paginate(10);
到
$user_dispatches = Dispatch::where('user_id', Auth::id())->paginate(10)
在另一个项目中我试图用我的帖子数组返回一个视图,我也能够像这样分页......在PostController
public function index()
{
$posts = Post::where('user_id', Auth::id());
return view('admin.posts.index', ['posts'=>$posts->paginate(5)]);
}
如果在 laravel + Blade 上工作,有时我需要保留
all()
或 get()
,我所做的就是添加 toQuery()
函数以使其工作。就我而言,这段代码帮助我在 Blade 上进行分页,而无需更改索引函数:
public function index()
{
$users = User::all();
foreach ($users as $user) {
//some code I need
}
}
return view('users.index', ['users' => $users->toQuery()->paginate(5)]);
}