hasMany(ProductSKU::class, 'order_id', 'id'); } public function products(): HasManyThrough { return $this->hasManyThrough( Product::class, ProductSKU::class, 'order_id', 'id', 'id', 'product_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id', 'id'); } public function district(): BelongsTo { return $this->belongsTo(District::class); } public function area(): BelongsTo { return $this->belongsTo(Area::class); } public function objectType(): BelongsTo { return $this->belongsTo(ObjectType::class); } public function brigadier(): BelongsTo { return $this->belongsTo(User::class, 'brigadier_id', 'id'); } public function orderStatus(): BelongsTo { return $this->belongsTo(OrderStatus::class); } public function getNeeds(): array { $needs = []; foreach ($this->products_sku as $sku) { $needs[$sku->product_id]['needs'] = (isset($needs[$sku->product_id])) ? $needs[$sku->product_id]['needs'] + 1 : 1; } foreach ($needs as $productId => $quantity) { $needs[$productId]['sku'] = MafOrder::query() ->where('maf_orders.product_id', $productId) ->sum('maf_orders.in_stock'); } return $needs; } public function recalculateReadyToMount(): void { $result = true; foreach ($this->getNeeds() as $need) { if($need['sku'] < $need['needs']) { $result = false; break; } } if($this->order_status_id > self::STATUS_NEW) { $result = true; } $this->update(['ready_to_mount' => ($result) ? 'Да' : 'Нет']); } public function commonName(): Attribute { return Attribute::make( get: fn($value) => (string) $this->district->shortname . ', ' . $this->area->name . ', ' . $this->object_address, ); } public function productsWithCount(): Attribute { $products = $this->products; $ret = []; foreach ($products as $product) { if(isset($ret[$product->id])) { $ret[$product->id]['count'] += 1; } else { $ret[$product->id] = [ 'name' => $product->common_name, 'count' => 1, ]; } } $s = ''; foreach ($ret as $product) { $s .= $product['name'] . ' (' . $product['count'] . ')
'; } return Attribute::make( get: fn($value) => (string) $s, ); } }