热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

thinkphp6:数据库查询分页(thinkphp6.0.9/php8.0.14)

一,编写model和controller代码1,modelArticle.php


一,编写model和controller代码

1,model/Article.php

php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use think\facade\Db;

/**
* @mixin \think\Model
*/
class Article extends Model
{
//类名与表名不一致时在这里指定数据表名
protected $table = "media";

//page:当前页
//size: 每页的数量

public function getPageMedia($page,$size) {
//分页查询时用paginate方法
$result = Db::table("media")->where("isSale",1)->order(['isSale'=>'asc','id'=>'desc'])->paginate(['list_rows'=> $size, 'page' => $page]);
return $result;
}
}

2,controller/Article.php

php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\result\Result;
use think\Request;
use think\facade\Cache;
use app\model\Article as ArticleModel;

class Article extends BaseController
{
//分页查询多条media记录
public function pageMedia() {
$page = $this->request->param('page',1,'intval');
$size = $this->request->param('size',1,'intval');

$article = new ArticleModel();
$rows = $article->getPageMedia($page,$size);

if (sizeof($rows) == 0) {
return Result::Error(1,"没有符合条件的数据");
}
else {
return Result::Success($rows);
}
}
}

3,Result.php

php

namespace app\result;

use think\response\Json;

class Result {
//success
static public function Success($data):Json {
$rs = [
'code'=>0,
'msg'=>"success",
'data'=>$data,
];
return json($rs);
}
//error
static public function Error($code,$msg):Json {
$rs = [
'code'=>$code,
'msg'=>$msg,
'data'=>"",
];
return json($rs);
}
}

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com 


二,测试效果

访问:

http://127.0.0.1:8000/article/pagemedia?page=1&size=2

返回:



 


三,查看php和thinkphp的版本:

php:

root@lhdpc:~# php --version
PHP
8.0.14 (cli) (built: Dec 23 2021 11:52:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.
0.14, Copyright (c) Zend Technologies
with Zend OPcache v8.
0.14, Copyright (c), by Zend Technologies

thinkphp:

root@lhdpc:~# cd /data/php/admapi/
root@lhdpc:
/data/php/admapi# php think version
v6.
0.9

 


原文链接:https://www.cnblogs.com/architectforest/p/15746823.html



推荐阅读
author-avatar
mobiledu2502928311
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有