Causal.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. 'corrispettivo_fiscale',
  14. 'no_receipt',
  15. 'user_status',
  16. 'no_first',
  17. 'no_records',
  18. 'enabled'
  19. ];
  20. public function childs() {
  21. return $this->hasMany(\App\Models\Causal::class,'parent_id','id') ;
  22. }
  23. public function getTree()
  24. {
  25. $str = '';
  26. if ($this->parent_id != null)
  27. {
  28. $a = $this->recursiveName($this->parent_id, array($this->name));
  29. $a = array_reverse($a);
  30. $str = implode(" - ", $a);
  31. }
  32. else
  33. {
  34. $str = $this->name;
  35. }
  36. return $str;
  37. }
  38. public function recursiveName($parent_id, $array)
  39. {
  40. $x = \App\Models\Causal::findOrFail($parent_id);
  41. $array[] = $x->name;
  42. if ($x->parent_id != null)
  43. {
  44. return $this->recursiveName($x->parent_id, $array);
  45. }
  46. else
  47. {
  48. return $array;
  49. }
  50. }
  51. public function recursiveParent($parent_id, $array)
  52. {
  53. if ($parent_id == null)
  54. return $array;
  55. $x = \App\Models\Causal::findOrFail($parent_id);
  56. $array[] = $x->id;
  57. if ($x->parent_id != null)
  58. {
  59. return $this->recursiveParent($x->parent_id, $array);
  60. }
  61. else
  62. {
  63. return $array;
  64. }
  65. }
  66. }