thinkphp6: 數據庫查詢分頁(thinkphp 6.0.9/php 8.0.14)


一,編寫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://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/29/thinkphp6-shu-ju-ku-cha-xun-fen-ye-thinkphp-6-9-php-8-14/

         對應的源碼可以訪問這里獲取: 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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM