hasMany(DictDetail::class, 'dict_id', 'id'); } public static function checkCodeIsUnique($code, $ignore_id = 0) { return self::query()->where('code', $code)->where('id', '<>', $ignore_id)->exists(); } /** * 通过code获取配置项 * @param $code * @return array|mixed */ public static function byCodeGetDicts($code) { return Cache::tags('model')->remember('model:Dict:byCodeGetDicts:' . $code, Carbon::now()->addDays(1), function () use ($code) { $id = self::query()->where('code', $code)->value('id'); if (!$id) { return []; } return DictDetail::query()->where('dict_id', $id)->where('status', ModelStatusEnum::OK)->orderByDesc('sort')->select(['name', 'value', 'id'])->get()->toArray(); }); } /** * 根据code获取相应的选项 * @param $code * @param array $ids * @return array|mixed */ public static function byCodeAndIdsGetDicts($code, array $ids) { return Cache::tags('model')->remember('model:Dict:byCodeAndIdsGetDicts:' . $code . ':' . arr2str($ids, '_'), Carbon::now()->addDays(1), function () use ($code, $ids) { $id = self::query()->where('code', $code)->value('id'); if (!$id) { return []; } return DictDetail::query()->where('dict_id', $id)->whereIn('value', $ids)->where('status', ModelStatusEnum::OK)->orderByDesc('sort')->select(['name', 'value'])->get(); }); } /** * 根据code获取相应的选项名 * @param $code * @param $id * @return array|mixed */ public static function byCodeAndIdGetDict($code, $id) { return Cache::tags('model')->remember('model:Dict:byCodeAndIdGetDict:' . $code . ':' . $id, Carbon::now()->addDays(1), function () use ($code, $id) { $did = self::query()->where('code', $code)->value('id'); if (!$did) { return ''; } return DictDetail::query()->where('dict_id', $did)->where('value', $id)->where('status', ModelStatusEnum::OK)->value('name'); }); } /** * 根据name获取value * @param $code * @param $name * @return array|mixed */ public static function byCodeAndNameGetValue($code, $name) { return Cache::tags('model')->remember('model:Dict:byCodeAndNameGetValue:' . $code . ':' . $name, Carbon::now()->addDays(1), function () use ($code, $name) { $did = self::query()->where('code', $code)->value('id'); if (!$did) { return ''; } return DictDetail::query()->where('dict_id', $did)->where('name', $name)->where('status', ModelStatusEnum::OK)->value('value'); }); } /** * 查找并创建 * @param $code * @param $name * @return */ public static function firstOrCreateItem($code, $name) { $did = self::query()->where('code', $code)->value('id') ?? 0; if (!$did) return false; $re = DictDetail::query()->where('dict_id', $did)->where('name', $name)->where('status', ModelStatusEnum::OK)->first(); if ($re) { return $re; } return DictDetail::query()->create([ 'name' => $name, 'dict_id' => $did, 'value' => $name, ]); } }