L5 repository 使用分页

需要用到分页包

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

控制器中添加分页代码

$posts = $this->repository->findWhere($queryArray);
$currentPage = Paginator::resolveCurrentPage() - 1;
$perPage = 10;
$currentPageSearchResults = $posts->slice($currentPage * $perPage, $perPage)->all();
$posts = new LengthAwarePaginator($currentPageSearchResults, count($posts), $perPage);

在视图当中进行使用

{!! $posts->setPath('/example-path')->appends(Request::except('page'))->render() !!}


MongoRepository 可以通过继承 PagingAndSortingRepository 接口来实现分页查询。具体步骤如下: 1. 在 Repository 接口中继承 PagingAndSortingRepository 接口: ```java import org.springframework.data.repository.PagingAndSortingRepository; public interface UserRepository extends PagingAndSortingRepository<User, String> { } ``` 2. 在 Service 层中调用 Repository 的方法,并传入 Pageable 对象来实现分页查询: ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public Page<User> findAll(Pageable pageable) { return userRepository.findAll(pageable); } } ``` 3. 在 Controller 中调用 Service 的方法,并传入 Pageable 对象来接收分页查询结果: ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping("/users") public Page<User> getUsers(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size) { PageRequest pageRequest = PageRequest.of(page, size); return userService.findAll(pageRequest); } } ``` 以上是基于 Spring Data MongoDB 和 MongoRepository 实现分页查询的一个示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值