StatTree.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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->save();
  37. // create tree lines
  38. foreach ($this->rootLines as $line) {
  39. $line->copy(null, $instance);
  40. }
  41. return $instance;
  42. }
  43. public function clone($name) {
  44. // create stat tree
  45. $instance = new StatTree();
  46. $nextId = DB::select("select nextval('stat_tree_id_seq')");
  47. $instance->id = $nextId[0]->nextval;
  48. $instance->uid = Uuid::uuid4();
  49. $instance->name = $name;
  50. $instance->model = $this->model;
  51. $instance->slug = $this->slug . '-' . rand(100, 999);
  52. $instance->is_template = $this->is_template;
  53. $instance->pro_id = $this->pro_id;
  54. $instance->pro_scope_clause = $this->pro_scope_clause;
  55. $instance->save();
  56. // create tree lines
  57. foreach ($this->rootLines as $line) {
  58. $line->copy(null, $instance);
  59. }
  60. return $instance;
  61. }
  62. }