DistProductCategory.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /*
  26. * 关联产品参数
  27. */
  28. public function distProductParameter()
  29. {
  30. return $this->hasOne(DistProductParameter::class,'id','parameter_id');
  31. }
  32. public static function selectOptions(\Closure $closure = null)
  33. {
  34. $options = (new static())->withQuery($closure)->buildSelectOptions();
  35. return collect($options)->all();
  36. }
  37. public function getAllCategories($parentId = null)
  38. {
  39. // Retrieve categories with the specified parentId, or all if no parentId is specified
  40. $query = self::query();
  41. if ($parentId !== null) {
  42. $query->where('parent_id', $parentId);
  43. }
  44. $categories = $query->orderBy($this->orderColumn)->get();
  45. // If you want a hierarchical structure, you can recursively build it
  46. $categories->each(function ($category) {
  47. $category->children = $category->getAllCategories($category->id);
  48. });
  49. return $categories;
  50. }
  51. }