65 lines
1.9 KiB
PHP
65 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace app\service;
|
|
|
|
use app\BaseModel;
|
|
use app\Request;
|
|
use think\Collection;
|
|
use think\db\exception\DataNotFoundException;
|
|
use think\db\exception\DbException;
|
|
use think\db\exception\ModelNotFoundException;
|
|
use think\helper\Str;
|
|
use think\Paginator;
|
|
use think\Service;
|
|
|
|
class CurdService extends Service
|
|
{
|
|
static int $MAX_LIMIT = 1000;
|
|
|
|
/**
|
|
* @param Request $request
|
|
* @param BaseModel $model
|
|
* @param null $order
|
|
* @return Collection
|
|
* @throws DataNotFoundException
|
|
* @throws DbException
|
|
* @throws ModelNotFoundException
|
|
*/
|
|
public static function getList(Request $request, mixed $model, $order = null): Collection
|
|
{
|
|
$offset = (int)$request->param('offset', 0);
|
|
$limit = (int)$request->param('limit', 30);
|
|
$limit = min($limit, self::$MAX_LIMIT);
|
|
|
|
return $model->order(!is_null($order) ? $order : (string)$model->getPk(), 'desc')
|
|
->limit($offset, $limit)
|
|
->select();
|
|
}
|
|
|
|
/**
|
|
* @param Request $request
|
|
* @param BaseModel $model
|
|
* @param null $order
|
|
* @return Paginator
|
|
* @throws DbException
|
|
*/
|
|
public static function getPaginate(Request $request, mixed $model, $order = null)
|
|
{
|
|
$page = (int)$request->param('page', 1);
|
|
$page = max(1, $page);
|
|
$limit = (int)$request->param('limit', 30);
|
|
$limit = min($limit, self::$MAX_LIMIT);
|
|
// 前端自定义排序条件
|
|
$sort = $request->param('sort');
|
|
$sort_order = $request->param('order');
|
|
if (!empty($sort) && in_array($sort_order, ['desc', 'asc'])) {
|
|
$order = [Str::snake($sort) => $sort_order];
|
|
}
|
|
return $model->order(!is_null($order) ? $order : (string)$model->getPk(), 'desc')
|
|
->limit($page, $limit)
|
|
->paginate([
|
|
'list_rows' => $limit,
|
|
'page' => $page,
|
|
]);
|
|
}
|
|
} |