OrderView.php 2.2 KB

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