where('sgroup', $sgroup); } if (!empty($keys)) { if (is_array($keys)) { $model = $model->whereIn('skey', $keys); } else { $model = $model->where('skey', $keys); } } $listObj = $model->orderBy('squad', 'DESC')->orderBy('created_at', 'ASC')->get(); if (!empty($listObj)) { $result = $listObj->mapWithKeys(function ($item) use ($keys, $sgroup) { return [$item->skey => $item]; }); } return !empty($result) ? $result->toArray() : []; } /** * 根据key数据保存. * @param array $data 数据. * @param string $sgroup 分组. * @return bool */ public function saveByKeys(array $data, string $sgroup) { foreach ($data as $skey => $svalue) { $svalue = is_null($svalue) ? '' : $svalue; if ($svalue) { $svalue = trim((string)$svalue); } if ($obj = ConfigModel::query()->where('sgroup', $sgroup)->where('skey', $skey)->first()) { if ($obj->svalue !== $svalue) { // 前后有变化才执行保存. $obj->svalue = $svalue; $obj->save(); } } else { // 没有则创建. $setarr = [ 'name' => $skey, 'sgroup' => $sgroup, 'skey' => $skey, 'svalue' => $svalue, 'value_type' => 'string', 'tag_name' => 'input', ]; ConfigModel::query()->create($setarr); } } return true; } /** * 更新配置缓存. * @param $sgroup * @return bool * @throws \Psr\SimpleCache\InvalidArgumentException */ public function updateConfigCache($sgroup) { $arrConfig = $this->pickByKeys([], $sgroup); /** * @var Cache $cache */ $cache = make('cache'); $cacheKey = 'config:'. $sgroup; $cache->forever($cacheKey, $arrConfig); // 把config清除一下. $cache->delete('config'); return true; } /** * 从缓存获取单个配置(单个找不到走DB查一次). * @param string $skey 键名. * @param string $sgroup 分组. * @param mixed $default 默认值. * @return mixed * @throws \Psr\SimpleCache\InvalidArgumentException */ public function get(string $skey, string $sgroup, $default = null) { $cacheKey = 'config:'. $sgroup; /** * @var Cache $cache */ $cache = make('cache'); $data = $cache->get($cacheKey); if (isset($data[$skey])) { return $data[$skey]['svalue']; } else { $items = $this->pickByKeys([], $sgroup); $cache->forever($cacheKey, $items); $item = $items[$skey] ?? array(); if ($item) { return $item['svalue']; } else { return $default; } } } /** * 从缓存配置获取多个配置(根本不走DB). * @param array $keys 键名. * @param string $sgroup 分组. * @param array $default 默认值. * @return array * @throws \Psr\SimpleCache\InvalidArgumentException */ public function gets($keys, string $sgroup, $default = []) { /** * @var Cache $cache */ $cache = make('cache'); $cacheKey = 'config:'. $sgroup; $data = $cache->remember( $cacheKey, 60 * 60, function () { return ConfigModel::query()->orderBy('squad', 'DESC')->get(); } ); if (!is_null($sgroup)) { $data = collect($data)->where('sgroup', $sgroup); } if (empty($keys)) { return $data->pluck('svalue', 'skey'); } else { return $data->whereIn('skey', $keys)->pluck('svalue', 'skey'); } } }