http://xx.com/api/article/recommend?page=1&numberOfPage=2
//成功返回Json字段:
{
"code":200,
"message":"",
"data":{
"pagination":{
"currentPage":1,//当前页数
"totalPage":100,//总页数
},
"article":[
{
"title":"文章标题",
"summary":"文章摘要",
"content":"",//文章正文,富文本
"update_at":"1012362541", //文章修改的时间戳
"recommend":true //是否是推荐文章
},
{
"title":"文章标题",
"summary":"文章摘要",
"content":""//文章正文,富文本
"update_at":"1012362541", //文章修改的时间戳
"recommend":true //是否是推荐文章
},
]
}
}
//失败返回Json字段:
{
"code":403,
"error": "获取推荐文章失败或没有推荐文章"
}
【开发分工】:开后端分离。
【开发环境】:Laravel 框架 5.6 + php7.1 + phpStudy + Mysql
【完成分页前后端工程师的责任】:
1)前端工程师: 前端完成分页页面和文章列表页面,然后规定好访问该接口的请求(路由),为后端通过请求提供两个参数:page 当前第几页 和 numberOfPage 每页显示的个数。
2)后端工程师:后端 根据 前端工程师 规定的 请求 来 创建 对应的 路由Route--->控制器Controller-->模型Model--->方法function , 然后在方法中 通过request 对象 来获取到 前端提供的两个参数。 然后再通过 Eloquent数据库操作 中的 paginate()方法来获取到 对应的 数据。
Laravel框架 的 paginate($numberOfPage):会自动的 从 GET请求中获取到page参数,paginate方法完成分页之后通过dd或者dump打印出来数据 就会显示 第page页的数据 。page这个参数会被laravel的paginate方法自动获取,获取后显示对应页数的数据。
路由:
Route::get('article/recommend','Api\Article\RecommendController@queryRecommend')->name('queryRecommend');
控制器及其方法:
class RecommendController extends BaseController
{
//微信用户 获取推荐文章列表
public function queryRecommend(Request $request){
$numberOfPage = $request->numberOfPage; //每页显示几个。
$article = Article::where('recommend',1)->orderBy('updated_at','desc')->paginate($numberOfPage); //recommend=1为推荐。
if($article!=null){ //说明查出来数据了。
$articleJSON = json_encode($article);
$newArticle = json_decode($articleJSON);
$arrayArticle = $newArticle->data;
for($i=0;$irecommend==1){
$arrayArticle[$i]->recommend = true ;
}
if($arrayArticle[$i]->recommend==0){
$arrayArticle[$i]->recommend = false ;
}
}
return $this->success([
"pagination"=>["currentPage"=>$newArticle->current_page,"totalPage"=>$newArticle->last_page],
"article"=>$newArticle->data
], "获取推荐文章成功");
}else{
return $this->error("获取推荐文章失败或没有推荐文章", 403);
}
}
}
涉及到的方法:
protected function success($data = [], $msg = 'success'){
return response()->json([
"code"=>200,
"massage"=>$msg,
"data"=>$data
]);
}
protected function error($msg, $code = 0){
return response()->json([
'code' => $code,
'error' => $msg
]);
}
1. 你最好编写一段 下面的代码看一下【分页完成后】的 数据结构:
$articleInfo = Article::paginate($numberOfPage );
dd($articleInfo);
2. 然后再执行:
dd($articleInfo->current_page); 该对象中的current_page取不出来。
3. 然后在执行:
dd(json_encode($articleInfo)); 将$articleInfo转换成了json格式的字符串,查看一下当前的 结构。
4. 然后再执行:
$newArticle = json_decode(json_encode($articleInfo)); 将这个$articleInfo对象 转换成 标准格式的 对象。
dd($newArticle->current_pag);该对象中的current_page 可以取出来 。
5. 最后你可以在看一下$newArticle 与 $articleInfo 的结构有什么不同:
dd($newArticle);
dd($articleInfo);