OrderView.php 2.3 KB

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