HasCustomFields.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Traits;
  3. use App\Model\CustomFieldValue;
  4. trait HasCustomFields
  5. {
  6. /**
  7. * 基础关联:获取该模型实例关联的所有自定义值
  8. */
  9. public function customFieldValues()
  10. {
  11. return $this->hasMany(CustomFieldValue::class, 'model_id')->where('del_time', 0);
  12. }
  13. /**
  14. * 获取指定菜单下的自定义字段数据
  15. */
  16. public function getCustomFieldsByMenu($menuId)
  17. {
  18. // 预加载已经在 itemCommon 中完成,这里 get() 会直接使用缓存数据
  19. return $this->customFieldValues
  20. ->filter(function ($item) use ($menuId) {
  21. // 过滤属于该菜单的定义(因为 with 预加载了 definition)
  22. return $item->definition && $item->definition->menu_id == $menuId;
  23. })
  24. ->map(function ($item) {
  25. $definition = $item->definition;
  26. $value = $item->field_value;
  27. $url = null;
  28. // 1. 处理文件 URL 逻辑
  29. if ($definition->field_type === 'file' && $value) {
  30. // 调用之前写的 getFileShow,并传入当前模型的 top_depart_id
  31. // $url = (new FileUploadService())->getFileShow($value, $this->top_depart_id);
  32. $url = "";
  33. }
  34. return [
  35. 'definition_id' => $definition->id,
  36. 'key' => $definition->field_key,
  37. 'label' => $definition->field_label,
  38. 'type' => $definition->field_type,
  39. 'value' => $value,
  40. 'url' => $url, // 这一步是前端展示的关键
  41. ];
  42. })
  43. ->values(); // 重置集合索引
  44. }
  45. /**
  46. * 辅助方法:快速获取某个特定字段的值
  47. */
  48. public function getCustomFieldValueByKey($menuId, $fieldKey)
  49. {
  50. $item = $this->customFieldValues
  51. ->first(function ($val) use ($menuId, $fieldKey) {
  52. return $val->definition
  53. && $val->definition->menu_id == $menuId
  54. && $val->definition->field_key == $fieldKey;
  55. });
  56. return $item ? $item->field_value : null;
  57. }
  58. }