hasMany(CustomFieldValue::class, 'model_id')->where('del_time', 0); } /** * 获取指定菜单下的自定义字段数据 */ public function getCustomFieldsByMenu($menuId) { // 预加载已经在 itemCommon 中完成,这里 get() 会直接使用缓存数据 return $this->customFieldValues ->filter(function ($item) use ($menuId) { // 过滤属于该菜单的定义(因为 with 预加载了 definition) return $item->definition && $item->definition->menu_id == $menuId; }) ->map(function ($item) { $definition = $item->definition; $value = $item->field_value; $url = null; // 1. 处理文件 URL 逻辑 if ($definition->field_type === 'file' && $value) { // 调用之前写的 getFileShow,并传入当前模型的 top_depart_id // $url = (new FileUploadService())->getFileShow($value, $this->top_depart_id); $url = ""; } return [ 'definition_id' => $definition->id, 'key' => $definition->field_key, 'label' => $definition->field_label, 'type' => $definition->field_type, 'value' => $value, 'url' => $url, // 这一步是前端展示的关键 ]; }) ->values(); // 重置集合索引 } /** * 辅助方法:快速获取某个特定字段的值 */ public function getCustomFieldValueByKey($menuId, $fieldKey) { $item = $this->customFieldValues ->first(function ($val) use ($menuId, $fieldKey) { return $val->definition && $val->definition->menu_id == $menuId && $val->definition->field_key == $fieldKey; }); return $item ? $item->field_value : null; } }