OrderView.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. public $appends = ['common_name', 'products_with_count'];
  10. public function commonName(): Attribute
  11. {
  12. return Attribute::make(
  13. get: fn($value) => (string) $this->object_address . ', ' . $this->area_name . ', ' . $this->district_name,
  14. );
  15. }
  16. public function productsWithCount(): Attribute
  17. {
  18. $products = ProductSKU::query()->where('order_id', $this->id)->get(); //$this->products_sku;
  19. $ret = [];
  20. foreach ($products as $product) {
  21. if(isset($ret[$product->product->id])) {
  22. $ret[$product->product->id]['count'] += 1;
  23. } else {
  24. $ret[$product->product->id] = [
  25. 'name' => $product->product->article,
  26. 'count' => 1,
  27. ];
  28. }
  29. if($product->maf_order?->order_number) {
  30. $ret[$product->product->id]['order_numbers'][] = $product->maf_order?->order_number;
  31. }
  32. }
  33. $s = '';
  34. $openTag = '<div>';
  35. $closeTag = '</div>';
  36. foreach ($ret as $product) {
  37. $order_numbers = (isset($product['order_numbers'])) ? ' (' . implode(', ', array_unique($product['order_numbers'])) . ')' : '';
  38. $s .= $openTag . $product['name'] . ' - ' . $product['count'] . $order_numbers . $closeTag;
  39. }
  40. return Attribute::make(
  41. get: fn($value) => (string) $s,
  42. );
  43. }
  44. }