DistProductCategory.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Models;
  3. use Dcat\Admin\Traits\HasDateTimeFormatter;
  4. use Dcat\Admin\Traits\ModelTree;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Spatie\EloquentSortable\Sortable;
  7. class DistProductCategory extends Model implements Sortable
  8. {
  9. use HasDateTimeFormatter,
  10. ModelTree {
  11. ModelTree::boot as treeBoot;
  12. }
  13. use HasDateTimeFormatter;
  14. protected $table = 'dist_product_category';
  15. //名称
  16. protected $titleColumn = 'name';
  17. //排序
  18. protected $orderColumn = 'order';
  19. //父级
  20. protected $parentColumn = 'parent_id';
  21. protected $casts = [
  22. 'created_at' => 'datetime:Y-m-d H:i:s',
  23. 'updated_at' => 'datetime:Y-m-d H:i:s',
  24. ];
  25. protected $fillable = [
  26. 'name', 'parent_id', 'order','enabled','dist_user_id', // 假设已有的可填充字段
  27. ];
  28. /*
  29. * 关联产品参数
  30. */
  31. public function distProductParameter()
  32. {
  33. return $this->hasOne(DistProductParameter::class,'id','parameter_id');
  34. }
  35. public static function selectOptions(\Closure $closure = null)
  36. {
  37. $options = (new static())->withQuery($closure)->buildSelectOptions();
  38. return collect($options)->all();
  39. }
  40. public function getAllCategories($parentId = null)
  41. {
  42. // Retrieve categories with the specified parentId, or all if no parentId is specified
  43. $query = self::query();
  44. if ($parentId !== null) {
  45. $query->where('parent_id', $parentId);
  46. }
  47. $categories = $query->orderBy($this->orderColumn)->get();
  48. // If you want a hierarchical structure, you can recursively build it
  49. $categories->each(function ($category) {
  50. $category->children = $category->getAllCategories($category->id);
  51. });
  52. return $categories;
  53. }
  54. }