<?php
 namespace App\Console\Commands; use App\Models\ClientDomain; use App\Models\ClientProduct; use App\Models\InvoiceItem; use Illuminate\Console\Command; class SyncInvoiceItemsRelatedServiceId extends Command { protected $signature = 'invoice:sync-related-service-ids'; protected $description = 'Sync related_service_id for existing invoice items based on domain_name and product_id'; public function handle() { $this->info('Starting to sync related fields for invoice items...'); $updated = 0; $skipped = 0; InvoiceItem::with('invoice') ->chunk(100, function ($items) use (&$updated, &$skipped) { foreach ($items as $item) { $relatedServiceId = null; $relatedType = $item->type; $relatedId = null; $needsUpdate = false; if ($item->type === 'domain' && $item->domain_name) { $domain = ClientDomain::where('domain', $item->domain_name)->first(); if ($domain) { $relatedServiceId = $domain->id; $relatedId = $domain->tld_id; $needsUpdate = true; } } if ($item->type === 'product' && $item->product_id) { $serviceQuery = ClientProduct::where('product_id', $item->product_id); if ($item->domain_name) { $serviceQuery->where('domain', $item->domain_name); } $service = $serviceQuery->first(); if ($service) { $relatedServiceId = $service->id; $relatedId = $service->product_id; $needsUpdate = true; } } if ($needsUpdate) { $item->update([ 'related_service_id' => $relatedServiceId, 'related_type' => $relatedType, 'related_id' => $relatedId, ]); $updated++; } else { $skipped++; } } }); $this->info('Sync completed!'); $this->info("Updated: {$updated} invoice items"); $this->info("Skipped: {$skipped} invoice items (no matching service/domain found)"); return 0; } } 