StatTree.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. use Ramsey\Uuid\Uuid;
  7. class StatTree extends Model
  8. {
  9. protected $table = 'stat_tree';
  10. public $timestamps = false;
  11. public function getRouteKeyName()
  12. {
  13. return 'uid';
  14. }
  15. public function pro(){
  16. return $this->hasOne(Pro::class, 'id', 'pro_id');
  17. }
  18. public function lines(){
  19. return $this->hasMany(StatTreeLine::class, 'stat_tree_id', 'id')->orderBy('id', 'ASC');
  20. }
  21. public function rootLines(){
  22. return $this->hasMany(StatTreeLine::class, 'stat_tree_id', 'id')->whereNull('parent_stat_tree_line_id')->orderBy('tree_order_position_index', 'ASC');
  23. }
  24. public function instantiateForPro(Pro $pro) {
  25. // create stat tree
  26. $instance = new StatTree();
  27. $nextId = DB::select("select nextval('stat_tree_id_seq')");
  28. $instance->id = $nextId[0]->nextval;
  29. $instance->uid = Uuid::uuid4();
  30. $instance->name = $this->name;
  31. $instance->model = $this->model;
  32. $instance->slug = $this->slug . ':' . $pro->uid;
  33. $instance->is_template = false;
  34. $instance->pro_id = $pro->id;
  35. $instance->pro_scope_clause = $this->pro_scope_clause;
  36. $instance->template_stat_tree_id = $this->id;
  37. $instance->save();
  38. // create tree lines
  39. foreach ($this->rootLines as $line) {
  40. $line->copy(null, $instance);
  41. }
  42. return $instance;
  43. }
  44. public function clone($name) {
  45. // create stat tree
  46. $instance = new StatTree();
  47. $nextId = DB::select("select nextval('stat_tree_id_seq')");
  48. $instance->id = $nextId[0]->nextval;
  49. $instance->uid = Uuid::uuid4();
  50. $instance->name = $name;
  51. $instance->model = $this->model;
  52. $instance->slug = $this->slug . '-' . rand(100, 999);
  53. $instance->is_template = $this->is_template;
  54. $instance->pro_id = $this->pro_id;
  55. $instance->pro_scope_clause = $this->pro_scope_clause;
  56. $instance->copied_from_stat_tree_id = $this->id;
  57. $instance->save();
  58. // create tree lines
  59. foreach ($this->rootLines as $line) {
  60. $line->copy(null, $instance);
  61. }
  62. return $instance;
  63. }
  64. }