'integer', 'sort' => 'integer', 'status' => 'integer', 'deleted' => 'boolean', 'create_time' => 'datetime', 'update_time' => 'datetime', ]; // 状态常量 const STATUS_NORMAL = 0; // 正常 const STATUS_DISABLED = 1; // 停用 // 状态映射 const STATUS_MAP = [ self::STATUS_NORMAL => '正常', self::STATUS_DISABLED => '停用', ]; /** * 获取状态文本 * * @return string */ public function getStatusTextAttribute(): string { return self::STATUS_MAP[$this->status] ?? '未知'; } /** * 获取字典类型 * * @return BelongsTo */ public function dictType(): BelongsTo { return $this->belongsTo(SystemDictType::class, 'dict_type', 'type'); } /** * 检查是否为正常状态 * * @return bool */ public function isNormal(): bool { return $this->status == self::STATUS_NORMAL; } /** * 检查是否为停用状态 * * @return bool */ public function isDisabled(): bool { return $this->status == self::STATUS_DISABLED; } /** * 启用字典数据 * * @return bool */ public function enable(): bool { return $this->update(['status' => self::STATUS_NORMAL]); } /** * 停用字典数据 * * @return bool */ public function disable(): bool { return $this->update(['status' => self::STATUS_DISABLED]); } /** * 检查字典值是否已存在 * * @param string $value * @param string $dictType * @param int|null $excludeId * @return bool */ public static function valueExists(string $value, string $dictType, ?int $excludeId = null): bool { $query = static::where('value', $value)->where('dict_type', $dictType); if ($excludeId) { $query->where('id', '!=', $excludeId); } return $query->exists(); } /** * 根据字典类型和值获取字典数据 * * @param string $dictType * @param string $value * @return static|null */ public static function findByTypeAndValue(string $dictType, string $value): ?static { return static::where('dict_type', $dictType) ->where('value', $value) ->first(); } /** * 根据字典类型获取所有数据 * * @param string $dictType * @param bool $onlyActive * @return \Illuminate\Database\Eloquent\Collection */ public static function getByType(string $dictType, bool $onlyActive = false) { $query = static::where('dict_type', $dictType)->orderBy('sort'); if ($onlyActive) { $query->where('status', self::STATUS_NORMAL); } return $query->get(); } /** * 根据字典类型获取键值对数组 * * @param string $dictType * @param bool $onlyActive * @return array */ public static function getOptionsByType(string $dictType, bool $onlyActive = true): array { $query = static::where('dict_type', $dictType)->orderBy('sort'); if ($onlyActive) { $query->where('status', self::STATUS_NORMAL); } return $query->pluck('label', 'value')->toArray(); } /** * 根据字典类型和值获取标签 * * @param string $dictType * @param string $value * @return string|null */ public static function getLabelByTypeAndValue(string $dictType, string $value): ?string { $dictData = static::findByTypeAndValue($dictType, $value); return $dictData ? $dictData->label : null; } /** * 获取字典数据的下一个排序值 * * @param string $dictType * @return int */ public static function getNextSort(string $dictType): int { $maxSort = static::where('dict_type', $dictType)->max('sort'); return $maxSort ? $maxSort + 1 : 1; } }