创建模型

This commit is contained in:
2025-05-12 09:04:46 +08:00
parent fc327e9f48
commit 8ee9ab1b92
19 changed files with 594 additions and 139 deletions

View File

@@ -26,6 +26,7 @@ DB_PORT=3306
DB_DATABASE=cc_admin
DB_USERNAME=root
DB_PASSWORD=root
DB_PREFIX=nl_
SESSION_DRIVER=file
SESSION_LIFETIME=120

View File

@@ -0,0 +1,312 @@
<?php
namespace App\BaseApp;
use App\Models\AdminModel;
use App\Service\common\JWTService;
use App\Service\common\UtilsService;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class BaseNotAuthService
{
/**
* @var mixed 单例实例,确保该类只有一个全局实例
*/
protected static mixed $_instance;
/**
* @var object 工具类对象,用于提供通用的功能方法
*/
protected object $utils;
/**
* @var int 用户ID默认值为0表示未登录状态
*/
protected int $userId = 0;
/**
* @var array 用户信息
*/
protected array $userInfo = [];
/**
* @var object 数据模型对象,用于数据库操作
*/
protected $model;
/**
* @var array 查询的字段
*/
protected array $selectField = ['*'];
/**
* @var array 查询条件Between
*/
protected array $whereBetween = [];
/**
* @var array 排序条件
*/
protected array $orderBy = [
'name' => 'id',
'sort' => 'desc',
];
/**
* @var array 查询条件
*/
protected array $where = [
['deleted_at', '=', 0]
];
/**
* @var array 查询条件In
*/
protected array $whereIn = [];
/**
* @var array 下拉列表字段
*/
protected array $optionField = ['id', 'name'];
/**
* @var array 下拉列表字段
*/
protected array $queryField = [];
/**
* @var array 关联加载
*/
protected array $with = [];
/**
* @var string 时间字段
*/
protected string $timeField = 'created_at';
public function __construct()
{
try {
$this->userInfo = JWTService::getInstance()->getToken()->getUserInfo();
$this->userId = $this->userInfo['id'] ?? 0;
} catch (Exception $e) {
$this->userId = 0;
}
$this->utils = UtilsService::getInstance();
}
/**
* 获取实例
* @return null|static
*/
public static function getInstance(): null|static
{
$name = get_called_class();
if (!isset(self::$_instance[$name])) {
self::$_instance[$name] = new static();
}
return self::$_instance[$name];
}
/**
* 获取列表数据
*
* 本函数负责根据设定的条件,从数据库中查询并返回分页后的数据列表
* 它会根据空值条件动态地修改查询,以实现灵活的查询需求
*
* @return array 返回包含分页信息和数据列表的数组
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getPageList($isArr = true, $isGetWhere = true): array
{
// 初始化查询条件
if ($isGetWhere === true) $this->getWhere();
// 获取范围查询条件
$searchTime = request()->get('search_time');
if (!empty($searchTime)) {
$this->getWhereBetween($searchTime);
}
// 执行数据库查询,根据条件动态构建查询语句
$result = $this->model::when(!empty($this->with), function ($query) {
// 如果关联加载条件存在,则添加关联加载
$query->with($this->with);
})
->when(!empty($this->where), function ($query) {
// 如果查询条件存在,则添加查询条件
$query->where($this->where);
})
->when(!empty($this->whereIn), function ($query) {
// 如果查询条件存在,则添加查询条件
$query->whereIn($this->whereIn[0], $this->whereIn[1]);
})
->when(!empty($this->whereBetween), function ($query) {
// 如果范围查询条件存在,则添加范围查询
$query->whereBetween($this->whereBetween[0], $this->whereBetween[1]);
})
->when(!empty($this->orderBy), function ($query) {
// 如果排序条件存在,则添加排序条件
$query->orderBy($this->orderBy['name'], $this->orderBy['sort']);
})
->select($this->selectField)
// 执行分页查询每页返回10条记录
->paginate(request()->get('pageSize', 20));
if ($isArr === true) {
$result = $result->toArray() ?? [];
// 返回分页信息和数据列表
return [
'page' => $result['current_page'],
'size' => $result['per_page'],
'page_count' => $result['last_page'],
'total' => $result['total'],
'items' => $result['data'],
];
}
// 返回分页信息和数据列表
return [
'page' => $result->currentPage(),
'size' => $result->perPage(),
'page_count' => $result->lastPage(),
'total' => $result->total(),
'items' => $result->items(),
];
}
/**
* 获取下拉列表数据
* @return mixed
*/
public function getOption(): mixed
{
$this->getWhere();
return $this->model::when(!empty($this->where), function ($query) {
$query->where($this->where);
})->when(!empty($this->whereIn), function ($query) {
$query->where($this->whereIn[0], $this->whereIn[1]);
})->orderBy($this->orderBy['name'], $this->orderBy['sort'])->get($this->optionField);
}
/**
* 详情
*
* @param $id
* @return mixed
* @throws Exception
*/
public function getDetail($id): mixed
{
$info = $this->model::with($this->with)->select($this->selectField)->find($id);
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
return $info;
}
/**
* 新增
* @param $params
* @return mixed
*/
public function insert($params): mixed
{
if (!array_key_exists('created_at', $params)) {
$params['created_at'] = time();
}
// return $this->model::insertGetId($this->utils->truncatedOss($params));
return $this->model::insertGetId($params);
}
/**
* 编辑
* @param $id
* @param $params
* @return mixed
* @throws Exception
*/
public function save($id, $params): mixed
{
if (empty(trim($id))) {
$this->utils->errorThrow('参数错误');
}
$this->where[] = ['id', '=', $id];
// 软删除
$info = $this->model::where($this->where)->first();
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
if (!array_key_exists('updated_at', $params)) {
$params['updated_at'] = time();
}
// return $this->model::where('id', $id)->update($this->utils->truncatedOss($params));
return $this->model::where('id', $id)->update($params);
}
/**
* 删除
*
* @param $id
* @return mixed|true
* @throws Exception
*/
public function del($id): mixed
{
// 软删除
$info = $this->model::whereIn('id', $id)->get(['id']);
if (empty($info)) {
return $this->utils->notFound('数据不存在');
}
if ($this->model::whereIn('id', $id)->update([
'deleted_at' => time(),
'updated_at' => time()
])) {
return true;
} else {
$this->utils->errorThrow('删除失败');
}
}
/**
* 获取查询条件
* @return void
*/
protected function getWhere(): void
{
$query = request()->query();
if (!empty($this->queryField)) {
foreach ($this->queryField as $key => $value) {
if (in_array($key, array_keys($query))) {
if (!empty($query[$key] ?? '') || $query[$key] == '0') {
switch ($value) {
case '=':
$this->where[] = [$key, $value, $query[$key]];
break;
case 'like':
$this->where[] = [$key, $value, '%' . $query[$key] . '%'];
break;
default:
break;
}
}
}
}
}
}
/**
* 获取时间范围查询条件
* @param $searchTime
* @return void
*/
protected function getWhereBetween($searchTime): void
{
$this->whereBetween = [$this->timeField, [strtotime($searchTime[0] ?? date('Y-m-01 00:00:00')), strtotime(date('Y-m-d 23:59:59', strtotime($searchTime[1])) ?? date('Y-m-d 23:59:59'))]];
}
}

View File

@@ -2,7 +2,7 @@
namespace App\BaseApp;
use App\Models\UserModel;
use App\Models\AdminModel;
use App\Service\common\JWTService;
use App\Service\common\UtilsService;
use Exception;
@@ -25,6 +25,10 @@ class BaseService
* @var int 用户ID默认值为0表示未登录状态
*/
protected int $userId = 0;
/**
* @var int 角色ID默认值为0表示未登录状态
*/
protected int $roleId = 0;
/**
* @var array 用户信息
@@ -36,11 +40,6 @@ class BaseService
*/
protected $model;
/**
* @var bool 是否需要验证用户权限
*/
protected bool $isAuth = true;
/**
* @var array 查询的字段
*/
@@ -93,17 +92,9 @@ class BaseService
public function __construct()
{
if ($this->isAuth) {
$this->userInfo = JWTService::getInstance()->getToken()->getUserInfo();
$this->userId = $this->userInfo['id'] ?? 0;
} else {
try {
$this->userInfo = JWTService::getInstance()->getToken()->getUserInfo();
$this->userId = $this->userInfo['id'] ?? 0;
} catch (Exception $e) {
$this->userId = 0;
}
}
$this->roleId = $this->userInfo['role_id'] ?? 0;
$this->utils = UtilsService::getInstance();
}

View File

@@ -3,20 +3,20 @@
namespace App\Http\Controllers\Api;
use App\BaseApp\BaseController;
use App\Service\UserService;
use App\Service\AdminService;
use Exception;
use Illuminate\Http\JsonResponse;
class UserController extends BaseController
class AdminController extends BaseController
{
//
public function __construct()
{
parent::__construct();
$this->service = UserService::getInstance();
$this->insertField = [ 'account', 'nick_name', 'password', 'role_id' ];
$this->updateField = [ 'id', 'account', 'nick_name', 'role_id' ];
$this->service = AdminService::getInstance();
$this->insertField = [ 'phone', 'nick_name', 'password', 'role_id' ];
$this->updateField = [ 'id', 'phone', 'nick_name', 'role_id' ];
$this->notRequest = ['qr_code', 'avatar', 'email', 'status'];
}
@@ -72,18 +72,4 @@ class UserController extends BaseController
'获取成功'
);
}
/**
* 获取当前用户信息
* @Method GET
* @return JsonResponse
* @throws Exception
*/
public function userStats(): JsonResponse
{
return jok(
$this->service->userStats(),
'获取成功'
);
}
}

View File

@@ -25,12 +25,12 @@ class LoginController extends BaseController
public function login()
{
$this->insertField = [
'account', 'password', 'remember'
'phone', 'password', 'remember'
];
$param = $this->checkRequiredFields(request()->post());
return jok(
$this->service->login($param['account'], $param['password']),
$this->service->login($param['phone'], $param['password']),
'登录成功'
);
}
@@ -44,12 +44,12 @@ class LoginController extends BaseController
public function register()
{
$this->insertField = [
'account', 'password', 'email', 'code'
'phone', 'password', 'email', 'code'
];
$param = $this->checkRequiredFields(request()->post());
return jok(
$this->service->register($param['account'], $param['password'], $param['email'], $param['code']),
$this->service->register($param['phone'], $param['password'], $param['email'], $param['code']),
'登录成功'
);
}

View File

@@ -4,10 +4,10 @@ namespace App\Models;
use App\BaseApp\BaseModel;
class UserModel extends BaseModel
class AdminModel extends BaseModel
{
protected $table = 'cc_admin';
protected $table = 'admin';
/**
* The attributes that are mass assignable.
*

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class AdminNoticeModel extends BaseModel
{
protected $table = 'admin_notice';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class ApiOpLogModel extends BaseModel
{
protected $table = 'api_op_log';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

17
app/Models/FileModel.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class FileModel extends BaseModel
{
protected $table = 'file';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

17
app/Models/MenuModel.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class MenuModel extends BaseModel
{
protected $table = 'menu';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class RoleMenuRelationModel extends BaseModel
{
protected $table = 'role_menu_relations';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

17
app/Models/RoleModel.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
class RoleModel extends BaseModel
{
protected $table = 'role';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

View File

@@ -1,48 +0,0 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@@ -4,23 +4,24 @@ namespace App\Service;
use App\BaseApp\BaseService;
use App\Enum\UserStatusEnum;
use App\Models\CollectionModel;
use App\Models\MenuModel;
use App\Models\RoleMenuRelationModel;
use App\Models\RoleModel;
use App\Models\UserModel;
use App\Models\UserPayModel;
use App\Models\AdminModel;
use App\Service\common\RedisService;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class UserService extends BaseService
class AdminService extends BaseService
{
public function __construct()
{
parent::__construct();
$this->selectField = [ 'id', 'account', 'nick_name', 'avatar', 'email', 'balance', 'is_sys_notifications', 'is_collection_notifications', 'is_marketing_notifications', 'qr_code', 'role_id', 'ip', 'ip_table', 'status', 'last_reset_password_at', 'created_at', 'updated_at', 'deleted_at', ];
$this->model = UserModel::class;
$this->selectField = [ 'id', 'phone', 'nick_name', 'avatar', 'email', 'balance', 'is_sys_notifications', 'is_collection_notifications', 'is_marketing_notifications', 'qr_code', 'role_id', 'ip', 'ip_table', 'status', 'last_reset_password_at', 'created_at', 'updated_at', 'deleted_at', ];
$this->model = AdminModel::class;
$this->queryField = [
'account' => 'like',
'phone' => 'like',
'nick_name' => 'like',
'email' => 'like',
'role_id' => '=',
@@ -74,7 +75,7 @@ class UserService extends BaseService
{
$params['ip_table'] = json_encode([]);
$params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
$existsUser = $this->model::where('account', $params['account'])->whereOr('email', $params['email'])->exists();
$existsUser = $this->model::where('phone', $params['phone'])->whereOr('email', $params['email'])->exists();
if ($existsUser) {
$this->utils->errorThrow('账号或邮箱已存在');
}
@@ -176,35 +177,62 @@ class UserService extends BaseService
];
$result = $this->getDetail($this->userId);
$result['created_day_at'] = format_time(strtotime($result['created_at']), 'Y-m-d');
$result['account'] = desensitization($result['account']);
$result['phone'] = desensitization($result['phone']);
return $result;
}
/**
* 用户统计
* @return array[]
* 获取菜单列表
* @return array
*/
public function userStats()
public function menu(): array
{
$payProject = UserPayModel::where('user_id', $this->userId)->count();
$collection = CollectionModel::where('user_id', $this->userId)->count();
$role = $this->userInfo['role_name'];
return [
'pay_project' => [
'label' => '已购项目',
'value' => $payProject,
'icon' => 'shopping-bag'
],
'collection' => [
'label' => '我的收藏',
'value' => $collection,
'icon' => 'heart'
],
'role' => [
'label' => '用户类型',
'value' => $role,
'icon' => 'user'
],
if ($this->roleId !== 1) {
// 从redis获取菜单列表
$redis = RedisService::getInstance()->init(config('xk.redis.menu_key'))->get($this->roleId);
// $redis = null;
if (!empty($redis)) {
return json_decode($redis, true);
}
}
// 如果没有数据则从数据库获取菜单列表
$selectField = [
'id', 'pid', 'title', 'icon', 'name', 'affix_tab', 'path', 'component', 'redirect', 'keep_alive', 'hide_in_menu', 'badge', 'badge_type', 'badge_variants', 'iframe_src', 'sort', 'query', 'created_at'
];
if ($this->roleId === 1) {
$menuList = MenuModel::where('deleted_at', 0)->orderBy('sort', 'asc')->get($selectField);
} else {
$menuIds = RoleMenuRelationModel::where('role_id', $this->roleId)->pluck('menu_id');
$menuList = MenuModel::where('deleted_at', 0)->whereIn('id', $menuIds)->orderBy('sort', 'asc')->get($selectField);
}
$resultMenus = [];
foreach ($menuList as $menu) {
$resultMenus[] = [
'id' => $menu->id,
'name' => $menu->name,
'path' => $menu->path,
'component' => $menu->component,
'redirect' => $menu->redirect,
'pid' => $menu->pid,
'sort' => $menu->sort,
'meta' => [
'title' => $menu->title,
'icon' => $menu->icon,
'keepAlive' => !$menu->keep_alive,
'hideInMenu' => (bool)$menu->hide_in_menu,
'affixTab' => !$menu->affix_tab,
'order' => $menu->sort,
'iframeSrc' => $menu->iframe_src,
]
];
}
$result = $this->utils->tree($resultMenus);
// 根据sort排序多层
usort($result, function ($a, $b) {
return $a['meta']['order'] - $b['meta']['order'];
});
// 缓存菜单列表到redis
RedisService::getInstance()->init(config('xk.redis.menu_key'))->set($this->roleId, json_encode($result), 3600);
return $result;
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Service;
use App\BaseApp\BaseService;
use App\Models\FileModel;
use App\Models\ProjectModel;
use App\Models\RoleModel;
use App\Models\UserModel;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class FileService extends BaseService
{
public function __construct()
{
parent::__construct();
$this->selectField = ['id', 'user_id', 'url', 'type', 'created_at', 'updated_at', 'deleted_at'];
$this->model = FileModel::class;
}
/**
* 获取文件列表
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function list(): array
{
return $this->getPageList();
}
public function detail($id)
{
return $this->getDetail($id);
}
/**
* 文件下拉列表
* @return mixed
*/
public function option()
{
$this->optionField = ['id', 'url'];
return $this->getOption();
}
/**
* 创建文件
* @param $params
* @return mixed
* @throws Exception
*/
public function create($params): mixed
{
return $this->insert($params);
}
/**
* 编辑文件
* @param $id
* @param $params
* @return mixed
* @throws Exception
*/
public function update($id, $params): mixed
{
return $this->save($id, $params);
}
/**
* 删除文件
* @param $ids
* @return mixed|true
* @throws Exception
*/
public function delete($ids): mixed
{
return $this->del($ids);
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Service;
use App\Models\UserModel;
use App\Models\AdminModel;
use App\Service\common\JWTService;
use App\Service\common\UtilsService;
use Exception;
@@ -32,17 +32,17 @@ class LoginService
/**
* 登录
* @param $account
* @param $phone
* @param $password
* @return array
* @throws Exception
*/
public function login($account, $password): array
public function login($phone, $password): array
{
$userModel = UserModel::with(['roles:id,name,value'])->where('account', $account)->first();
$userModel = AdminModel::with(['roles:id,name,value'])->where('phone', $phone)->first();
if (empty($userModel)) {
UtilsService::getInstance()->errorThrow('用户或密码错误!');
// return $this->register($account, $password);
// return $this->register($phone, $password);
}
if (!password_verify($password, $userModel->password)) {
@@ -54,7 +54,7 @@ class LoginService
if (!in_array(get_ip(), $ipTable)) {
$ipTable[] = get_ip();
}
$update = UserModel::where('id', $userModel->id)->update([
$update = AdminModel::where('id', $userModel->id)->update([
'ip' => get_ip(),
'ip_table' => json_encode($ipTable),
'updated_at' => get_time()
@@ -64,11 +64,11 @@ class LoginService
UtilsService::getInstance()->errorThrow('更新失败!');
}
$userModel = UserModel::where('id', $userModel->id)->first();
$userModel = AdminModel::where('id', $userModel->id)->first();
}
$result = [
'id' => $userModel->id,
'account' => $userModel->account,
'phone' => $userModel->phone,
'nick_name' => $userModel->nick_name,
'avatar' => $userModel->avatar,
'email' => $userModel->email,
@@ -84,22 +84,22 @@ class LoginService
/**
* 注册
* @param $account
* @param $phone
* @param $password
* @param $email
* @param $code
* @return array
* @throws Exception
*/
public function register($account, $password, $email, $code): array
public function register($phone, $password, $email, $code): array
{
$userModel = UserModel::where('account', $account)->first();
$userModel = AdminModel::where('phone', $phone)->first();
if ($userModel) {
UtilsService::getInstance()->errorThrow('账号已被占用!');
}
$createModel = UserModel::create([
'account' => $account,
$createModel = AdminModel::create([
'phone' => $phone,
'email' => $email,
'password' => password_hash($password, PASSWORD_DEFAULT),
'nick_name' => '新用户'. Str::random(),
@@ -114,11 +114,11 @@ class LoginService
UtilsService::getInstance()->errorThrow('注册失败!');
}
$userInfo = UserModel::with(['roles:id,name,value'])->where('id', $createModel->id)->first();
$userInfo = AdminModel::with(['roles:id,name,value'])->where('id', $createModel->id)->first();
$result = [
'id' => $userInfo->id,
'account' => $userInfo->account,
'phone' => $userInfo->phone,
'nick_name' => $userInfo->nick_name,
'avatar' => $userInfo->avatar,
'email' => $userInfo->email?? '',

View File

@@ -5,7 +5,7 @@ namespace App\Service\common;
use App\BaseApp\BaseService;
use App\Models\ProjectModel;
use App\Models\RoleModel;
use App\Models\UserModel;
use App\Models\AdminModel;
use App\Service\common\upload\LocalhostStorageService;
use App\Service\common\upload\QiniuStorageService;
use App\Service\FileService;

View File

@@ -53,7 +53,7 @@ return [
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix' => env('DB_PREFIX', ''),
'prefix_indexes' => true,
'strict' => true,
'engine' => null,

View File

@@ -16,6 +16,6 @@ UtilsService::class::getInstance()->autoRouteRegister([
Route::group([], function () {
UtilsService::class::getInstance()->autoRouteRegister([
'user' => \App\Http\Controllers\Api\UserController::class, // 用户控制器
'user' => \App\Http\Controllers\Api\AdminController::class, // 用户控制器
]);
});