87 lines
1.9 KiB
PHP
87 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace app\common\logic;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use support\exception\BusinessException;
|
|
|
|
class BaseLogic
|
|
{
|
|
/**
|
|
* 获取列表
|
|
*/
|
|
public function getList(array $params, string $modelClass)
|
|
{
|
|
$query = $modelClass::query();
|
|
|
|
// 你可以在此处添加分页、排序等功能
|
|
if (isset($params['page']) && isset($params['per_page'])) {
|
|
$query->paginate($params['per_page'], ['*'], 'page', $params['page']);
|
|
}
|
|
|
|
return $query->get();
|
|
}
|
|
|
|
/**
|
|
* 获取单个记录
|
|
*/
|
|
public function getDetail(int $id, string $modelClass)
|
|
{
|
|
$record = $modelClass::find($id);
|
|
if (!$record) {
|
|
throw new BusinessException("记录不存在", 404);
|
|
}
|
|
|
|
return $record;
|
|
}
|
|
|
|
/**
|
|
* 创建记录
|
|
*/
|
|
public function create(array $data, string $modelClass)
|
|
{
|
|
$model = new $modelClass;
|
|
$model->fill($data); // 根据字段填充数据
|
|
try {
|
|
$model->save();
|
|
} catch (\Throwable $e) {
|
|
throw new BusinessException("创建记录失败: " . $e->getMessage(), 500);
|
|
}
|
|
|
|
return $model;
|
|
}
|
|
|
|
/**
|
|
* 更新记录
|
|
*/
|
|
public function update(array $data, string $modelClass)
|
|
{
|
|
$record = $modelClass::find($data['id']);
|
|
if (!$record) {
|
|
throw new BusinessException("记录不存在", 404);
|
|
}
|
|
|
|
$record->update($data);
|
|
return $record;
|
|
}
|
|
|
|
/**
|
|
* 删除记录
|
|
*/
|
|
public function delete(int $id, string $modelClass)
|
|
{
|
|
$record = $modelClass::find($id);
|
|
if (!$record) {
|
|
throw new BusinessException("记录不存在", 404);
|
|
}
|
|
|
|
try {
|
|
$record->delete();
|
|
} catch (\Throwable $e) {
|
|
throw new BusinessException("删除记录失败: " . $e->getMessage(), 500);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|