Causal.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Causal extends Model
  6. {
  7. use HasFactory;
  8. protected $fillable = [
  9. 'parent_id',
  10. 'name',
  11. 'type',
  12. 'money',
  13. 'user_status',
  14. 'no_first',
  15. 'enabled'
  16. ];
  17. public function childs() {
  18. return $this->hasMany(\App\Models\Causal::class,'parent_id','id') ;
  19. }
  20. public function getTree()
  21. {
  22. $str = '';
  23. if ($this->parent_id != null)
  24. {
  25. $a = $this->recursiveName($this->parent_id, array($this->name));
  26. $a = array_reverse($a);
  27. $str = implode(" - ", $a);
  28. }
  29. else
  30. {
  31. $str = $this->name;
  32. }
  33. return $str;
  34. }
  35. public function recursiveName($parent_id, $array)
  36. {
  37. $x = \App\Models\Causal::findOrFail($parent_id);
  38. $array[] = $x->name;
  39. if ($x->parent_id != null)
  40. {
  41. return $this->recursiveName($x->parent_id, $array);
  42. }
  43. else
  44. {
  45. return $array;
  46. }
  47. }
  48. public function recursiveParent($parent_id, $array)
  49. {
  50. if ($parent_id == null)
  51. return $array;
  52. $x = \App\Models\Causal::findOrFail($parent_id);
  53. $array[] = $x->id;
  54. if ($x->parent_id != null)
  55. {
  56. return $this->recursiveParent($x->parent_id, $array);
  57. }
  58. else
  59. {
  60. return $array;
  61. }
  62. }
  63. }