Department.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Repositories\Models\Base;
  3. use App\Repositories\Models\Model;
  4. use Carbon\Carbon;
  5. use Illuminate\Support\Facades\Cache;
  6. use Prettus\Repository\Contracts\Transformable;
  7. use Prettus\Repository\Traits\TransformableTrait;
  8. /**
  9. * Class Department.
  10. *
  11. * @package namespace App\Repositories\Models;
  12. */
  13. class Department extends Model implements Transformable
  14. {
  15. use TransformableTrait;
  16. protected $table = 'base_departments';
  17. /**
  18. * The attributes that are mass assignable.
  19. *
  20. * @var array
  21. */
  22. protected $fillable = ['name', 'parent_id', 'sort', 'status'];
  23. protected static function booted()
  24. {
  25. self::language();
  26. }
  27. public function parent()
  28. {
  29. return $this->belongsTo(Department::class, 'parent_id', 'id');
  30. }
  31. public function getParentNameAttribute()
  32. {
  33. return self::query()->where('id', $this->attributes['parent_id'])->value('name');
  34. }
  35. /**
  36. * 根据name获取班级id
  37. * @param $name
  38. * @return mixed
  39. */
  40. public static function byNameGetId($name, $is_create = false)
  41. {
  42. return Cache::remember('model:Department:byNameGetId:' . $name, Carbon::now()->addDay(), function () use ($name, $is_create) {
  43. $id = self::query()->where('name', $name)->value('id') ?? 0;
  44. if ($id) return $id;
  45. if (!$is_create) return $id;
  46. $model = self::query()->create(['name' => $name]);
  47. return $model['id'];
  48. });
  49. }
  50. }