OrderView.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Models;
  3. use App\Models\Scopes\YearScope;
  4. use Illuminate\Database\Eloquent\Attributes\ScopedBy;
  5. use Illuminate\Database\Eloquent\Casts\Attribute;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Eloquent\SoftDeletes;
  8. #[ScopedBy([YearScope::class])]
  9. class OrderView extends Model
  10. {
  11. use SoftDeletes;
  12. const DEFAULT_SORT_BY = 'created_at';
  13. protected $table = 'orders_view';
  14. protected $fillable = [
  15. 'year',
  16. 'name',
  17. 'user_id',
  18. 'district_id',
  19. 'area_id',
  20. 'object_address',
  21. 'object_type_id',
  22. 'comment',
  23. 'installation_date',
  24. 'ready_date',
  25. 'brigadier_id',
  26. 'order_status_id',
  27. 'tg_group_name',
  28. 'tg_group_link',
  29. 'ready_to_mount',
  30. 'user_name',
  31. 'district_name',
  32. 'area_name',
  33. 'object_type_name',
  34. 'brigadier_name',
  35. 'order_status_name',
  36. ];
  37. public $appends = ['common_name', 'products_with_count'];
  38. public function commonName(): Attribute
  39. {
  40. return Attribute::make(
  41. get: fn($value) => (string) $this->object_address . ', ' . $this->area_name . ', ' . $this->district_name,
  42. );
  43. }
  44. public function productsWithCount(): Attribute
  45. {
  46. $products = ProductSKU::query()->where('order_id', $this->id)->get(); //$this->products_sku;
  47. $ret = [];
  48. foreach ($products as $product) {
  49. if(isset($ret[$product->product->id])) {
  50. $ret[$product->product->id]['count'] += 1;
  51. } else {
  52. $ret[$product->product->id] = [
  53. 'name' => $product->product->article,
  54. 'count' => 1,
  55. ];
  56. }
  57. if($product->maf_order?->order_number) {
  58. $ret[$product->product->id]['order_numbers'][] = $product->maf_order?->order_number;
  59. }
  60. }
  61. $s = '';
  62. $openTag = '<div>';
  63. $closeTag = '</div>';
  64. foreach ($ret as $product) {
  65. $order_numbers = (isset($product['order_numbers'])) ? ' (' . implode(', ', array_unique($product['order_numbers'])) . ')' : '';
  66. $s .= $openTag . $product['name'] . ' - ' . $product['count'] . $order_numbers . $closeTag;
  67. }
  68. return Attribute::make(
  69. get: fn($value) => (string) $s,
  70. );
  71. }
  72. }