# pip install pymysql
# pip install os
import pymysql
import os
# 数据库配置
db_config = {
'host': 'IP',
'port': 3306,
'user': 'root',
'password': 'PWD',
'database': 'DBNAME',
'charset': 'utf8mb4'
}
# 连接到数据库
connection = pymysql.connect(**db_config)
# 获取表字段
def get_table_structure(table_name):
with connection.cursor() as cursor:
cursor.execute(f"DESCRIBE {table_name}")
return cursor.fetchall()
# 驼峰命名
def convert_to_camel_case(snake_str):
components = snake_str.split('_')
return ''.join(x.capitalize() for x in components)
# 生成model代码
def generate_model_code(table_name, columns, package_name):
class_name = convert_to_camel_case(table_name) + "Model"
fields = ',\n '.join([f"'{column[0]}'" for column in columns])
model_code = f"""<?php
namespace app\\model\\{package_name};
use think\\Model;
class {class_name} extends Model
{{
protected $table = '{table_name}';
protected $fields = [
{fields}
];
}}
"""
return model_code
# 生成Controller代码
def generate_controller_code(table_name, columns, package_name):
class_name = convert_to_camel_case(table_name) + "Controller"
model_class_name = convert_to_camel_case(table_name) + "Model"
controller_code = f"""<?php
namespace app\\controller\\{package_name};
use app\\model\\{package_name}\\{model_class_name};
use think\\facade\\Request;
use think\\exception\\ValidateException;
use think\\response\\Json;
class {class_name}
{{
/**
* 获取列表(分页)
* @return Json
*/
public function listsAjax()
{{
$page = Request::get('page', 1);
$limit = Request::get('limit', 20);
$name = Request::get('name'); // 要查询的字段
$whereMap = [];
if (!empty($name)) $whereMap[] = ['name', 'like', "%{{$name}}%"];
$model = new {model_class_name}();
$count = $model->where($whereMap)->count();
$data = $model->where($whereMap)->limit(($page - 1) * $limit, $limit)->select()->toArray();
return json([
'status' => 1,
'msg' => '',
'data' => [
'page' => $page,
'totalPage' => ceil($count / $limit),
'limit' => $limit,
'totalNum' => $count,
'data' => $data
]
]);
}}
/**
* 保存信息
* @return Json
*/
public function saveAjax()
{{
$data = Request::post();
$model = new {model_class_name}();
try {{
if (!empty($data['id'])) {{
// 更新,不允许修改创建时间
unset($data['create_time']);
$data['modified_time'] = date('Y-m-d H:i:s');
$result = $model->strict(false)->where('id', $data['id'])->save($data);
}} else {{
unset($data['id']); // 删除空字符串等情况下的id属性
// 新增表数据
$result = $model->strict(false)->save($data);
}}
if (!empty($result)) {{
return json([
'status' => 1,'msg' => '操作成功','data' => []
]);
}} else {{
return json([
'status' => 0,'msg' => '操作失败,请重试','data' => []
]);
}}
}} catch (ValidateException $e) {{
return json([
'status' => 0,'msg' => '验证失败: ' . $e->getMessage(),'data' => []
]);
}} catch (\\Exception $e) {{
return json([
'status' => 0,'msg' => '异常: ' . $e->getMessage(),'data' => []
]);
}}
}}
/**
* 删除信息
* @return Json
*/
public function removeAjax()
{{
$id = Request::post('id');
if (empty($id)) {{
return json([
'status' => 0,
'msg' => '参数错误',
'data' => []
]);
}}
$model = new {model_class_name}();
$res = $model->where('id', $id)->delete();
if (!empty($res)) {{
return json([
'status' => 1,'msg' => '删除成功','data' => []
]);
}} else {{
return json([
'status' => 0,'msg' => '删除失败','data' => []
]);
}}
}}
/**
* 更新flag标志位
* @return Json
*/
public function updateFlagAjax()
{{
$id = Request::post('id');
$flag = Request::post('flag');
if (empty($id) || !isset($flag)) {{
return json([
'status' => 0,'msg' => '参数错误','data' => []
]);
}}
$model = new {model_class_name}();
$result = $model->where('id', $id)->update(['flag' => $flag,'modified_time'=>date('Y-m-d H:i:s')]);
if (!empty($result)) {{
return json([
'status' => 1,'msg' => '更新成功','data' => []
]);
}} else {{
return json([
'status' => 0,'msg' => '更新失败','data' => []
]);
}}
}}
}}
"""
return controller_code
# 生成route代码
def generate_route_code(table_name, package_name):
controller_class_name = convert_to_camel_case(table_name) + "Controller"
route_code = f"""<?php
use think\\facade\\Route;
Route::resource('{convert_to_camel_case(table_name)}', '{package_name}\\controller\\{controller_class_name}');
"""
return route_code
# 生成文件即文件代码
def generate_code_for_table(table_name, package_name):
columns = get_table_structure(table_name)
model_class_name = convert_to_camel_case(table_name) + "Model"
controller_class_name = convert_to_camel_case(table_name) + "Controller"
model_code = generate_model_code(table_name, columns, package_name)
controller_code = generate_controller_code(table_name, columns, package_name)
route_code = generate_route_code(table_name, package_name)
package_path = package_name.replace("\\", "/")
model_dir = os.path.join(package_path, 'model')
controller_dir = os.path.join(package_path, 'controller')
route_dir = os.path.join(package_path, 'route')
# 创建目录
os.makedirs(model_dir, exist_ok=True)
os.makedirs(controller_dir, exist_ok=True)
os.makedirs(route_dir, exist_ok=True)
with open(f"{model_dir}/{model_class_name}.php", "w") as model_file:
model_file.write(model_code)
with open(f"{controller_dir}/{controller_class_name}.php", "w") as controller_file:
controller_file.write(controller_code)
with open(f"{route_dir}/{convert_to_camel_case(table_name)}Route.php", "w") as route_file:
route_file.write(route_code)
print(f"{table_name}代码生成完毕")
def main(tables, package_name):
table_list = tables.split(',')
for table in table_list:
generate_code_for_table(table.strip(), package_name)
# 执行main方法
main('tbl_name', 'packageName')