DistProductCategory.php 2.0 KB

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