use Illuminate\Support\Facades\DB; // Reads storage/app/_barmodel_map.json (list of {source, png, working, ...}). // Appends a model-method block to each question's solution, idempotently: // re-runs replace the block after the sentinel rather than stacking copies. $SENT = "\n\n— Model method —\n"; $path = storage_path('app/_barmodel_map.json'); if (!is_file($path)) { echo "NO MAP at $path\n"; return; } $rows = json_decode(file_get_contents($path), true) ?: []; $updated=0; $created=0; $missing=0; $missSamples=[]; foreach ($rows as $r) { $src = $r['source'] ?? null; $png = $r['png'] ?? null; if (!$src || !$png) continue; $q = DB::table('questions')->where('source',$src)->first(['id']); if (!$q) { $missing++; if(count($missSamples)<10) $missSamples[]=$src; continue; } $block = $SENT . trim((string)($r['working'] ?? '')) . "\n[[model:$png]]"; $sol = DB::table('solutions')->where('question_id',$q->id)->orderBy('id')->first(['id','solution']); if ($sol) { $base = $sol->solution ?? ''; $cut = strpos($base, "— Model method —"); if ($cut !== false) $base = rtrim(substr($base, 0, $cut)); // drop old block DB::table('solutions')->where('id',$sol->id) ->update(['solution'=>$base.$block, 'updated_at'=>now()]); $updated++; } else { DB::table('solutions')->insert([ 'question_id'=>$q->id,'status_id'=>4,'source'=>'ai','user_id'=>2, 'solution'=>ltrim($block), 'created_at'=>now(),'updated_at'=>now(), ]); $created++; } } echo "attached: updated=$updated created=$created missing_question=$missing\n"; if ($missSamples) echo "missing eg: ".implode(' | ',$missSamples)."\n";