erp-backend/app/Models/SystemConfig.php
2026-04-01 17:07:04 +08:00

102 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SystemConfig extends Model
{
use HasFactory;
protected $fillable = [
'group',
'key',
'value',
'type',
'label',
'description',
'options',
'rules',
'sort',
'status',
];
protected $casts = [
'options' => 'array',
'rules' => 'array',
'sort' => 'integer',
];
/**
* 获取配置值
*/
public static function getValue($group, $key, $default = null)
{
$cacheKey = 'system_config_' . $group . '_' . $key;
return cache()->remember($cacheKey, 3600, function () use ($group, $key, $default) {
$config = self::where('group', $group)
->where('key', $key)
->where('status', 'active')
->first();
return $config ? $config->value : $default;
});
}
/**
* 设置配置值
*/
public static function setValue($group, $key, $value)
{
$config = self::updateOrCreate(
['group' => $group, 'key' => $key],
['value' => $value, 'status' => 'active']
);
// 清除缓存
cache()->forget('system_config_' . $group . '_' . $key);
cache()->forget('system_config_group_' . $group);
return $config;
}
/**
* 获取分组配置
*/
public static function getGroupConfigs($group)
{
$cacheKey = 'system_config_group_' . $group;
return cache()->remember($cacheKey, 3600, function () use ($group) {
return self::where('group', $group)
->where('status', 'active')
->orderBy('sort', 'asc')
->get()
->mapWithKeys(function ($config) {
return [$config->key => $config->value];
})
->toArray();
});
}
/**
* 清除配置缓存
*/
public static function clearCache($group = null, $key = null)
{
if ($group && $key) {
cache()->forget('system_config_' . $group . '_' . $key);
}
if ($group) {
cache()->forget('system_config_group_' . $group);
}
if (!$group && !$key) {
// 清除所有配置相关的缓存
cache()->forget('system_config_*');
}
}
}