houde_web_api/app/common/model/Teachers_strength/subject.php
2023-04-27 19:52:58 +08:00

170 lines
4.0 KiB
PHP

<?php
namespace app\common\model\Teachers_Strength;
use app\common\arw\adjfut\src\Validate;
use app\BaseModel;
use think\model\concern\SoftDelete;
use app\common\arw\adjfut\src\Excel;
use app\Request;
use app\common\exception\Tool;
use think\facade\Db;
class Subject extends BaseModel
{
use SoftDelete;
// 删除字段
protected $deleteTime = 'subject_delete_time';
// 设置主键名
protected $pk = 'subject_guid';
// 设置废弃字段
protected $disuse = [];
// 设置字段信息
protected $schema = [
"subject_id" => "int",
"subject_guid" => "string",
"subject_name" => "string",
"subject_sort" => "int",
"subject_create_time" => "datetime",
"subject_create_user_guid" => "string",
"subject_update_time" => "datetime",
"subject_update_user_guid" => "string",
"subject_delete_time" => "datetime",
"subject_delete_user_guid" => "string",
];
// 设置json类型字段
protected $json = [''];
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'datetime';
// 创建时间
protected $createTime = 'subject_create_time';
// 修改时间
protected $updateTime = 'subject_update_time';
// excel导入/下载模板表头
public const EXCELFIELD = [
'subject_name' => '科目名字',
'subject_sort' => '排序',
];
//排序字段
public $order_field = 'subject_sort';
/**
* 新增前
*/
public static function onBeforeInsert(self $model): void
{
// self::checkRepeatData($model);
Tool::sortInsertProc(
self::class,
$model->subject_sort,
);
$model->completeCreateField();
}
/**
* 更新前
*/
public static function onBeforeUpdate(self $model): void
{
// self::checkRepeatData($model);
Tool::sortEditProc(
self::class,
$model->subject_guid,
$model->subject_sort,
);
$model->completeUpdateField();
}
/**
* 删除前
*/
public static function onBeforeDelete(self $model): void
{
Tool::sortDeleteProc(self::class, $model->subject_guid);
$model->completeDeleteField();
}
/**
* 导出Excel
*/
public static function exportExcel($select)
{
$data = [[
'科目名字',
'排序'
]];
foreach ($select as $key => $val) {
$data[] = [
$val['subject_name'],
$val['subject_sort'],
];
}
$excel = (new Excel())->exporTsheet($data);
$excel->save('授课科目.xlsx');
}
/**
* 导入excel
*/
public static function importExcel($file)
{
$msg = [];
Db::startTrans();
try {
$excel = new Excel($file);
$data = $excel->parseExcel(
Tool::getExcelRule(self::EXCELFIELD),
[
'titleLine' => [1]
]
);
if (!$data) throwErrorMsg('excel无数据', 1);
$msg = [];
foreach ($data as $line => $value) {
try {
$model = self::importExcelInit($value);
$msg[] = "{$line} <span style='color:#27af49'>新增成功!</span><br>";
} catch (\Throwable $th) {
$msg[] = "{$line} <span style='color:red'>{$th->getMessage()}</span><br>";
}
}
Db::commit();
return implode(', ', $msg);
} catch (\Throwable $th) {
Db::rollback();
throw $th;
}
}
/**
* 导入excel初始化
*/
public static function importExcelInit($value)
{
$subject_name = $value['subject_name'];
$subject_sort = $value['subject_sort'];
return self::create([
'subject_name' => $subject_name,
'subject_sort' => $subject_sort,
]);
}
}