BankCategory.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Repositories\Models\Exam;
  3. use App\Repositories\Models\Model;
  4. use Illuminate\Support\Facades\DB;
  5. class BankCategory extends Model
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $table = 'exam_bank_categories';
  11. protected $guarded = [];
  12. /**
  13. * The attributes excluded from the model's JSON form.
  14. *
  15. * @var array
  16. */
  17. protected $hidden = [];
  18. public static function boot()
  19. {
  20. parent::boot(); // TODO: Change the autogenerated stub
  21. self::updated(function (BankCategory $bankCategory) {
  22. if ($bankCategory->isDirty('pid')) {
  23. $nodes = self::byIdGetParentIds($bankCategory->id);
  24. $nodes = '-' . arr2str($nodes, '-') . '-';
  25. DB::table('exam_bank_categories')->where('id', $bankCategory->id)->update(['nodes' => $nodes]);
  26. }
  27. });
  28. }
  29. public function parent()
  30. {
  31. return $this->belongsTo(self::class, 'pid');
  32. }
  33. public function children()
  34. {
  35. return $this->hasMany(self::class, 'pid');
  36. }
  37. public function setNodesAttribute($val)
  38. {
  39. $val = arr2str($val, '-');
  40. $this->attributes['nodes'] = "-{$val}-";
  41. }
  42. public static function byIdGetParentIds($id)
  43. {
  44. $ids = [$id];
  45. $pid = self::query()->where('id', $id)->value('pid');
  46. if ($pid) {
  47. $pid = self::byIdGetParentIds($pid);
  48. $ids = array_merge($ids, $pid);
  49. }
  50. return $ids;
  51. }
  52. }