$scope = function($q){ $q->where('source','like','% P1 %')->orWhere('source','like','% P2 %')->orWhere('source','like','% P3 %'); }; $rows = DB::table('questions')->where($scope) ->whereNotNull('explanation')->where('explanation','!=','') ->whereNotIn('id', function($q){ $q->select('question_id')->from('solutions'); }) ->get(['id','explanation']); $now = now(); $n = 0; foreach ($rows as $r) { DB::table('solutions')->insert([ 'question_id'=>$r->id, 'status_id'=>4, 'source'=>'ai', 'user_id'=>2, 'solution'=>$r->explanation, 'created_at'=>$now, 'updated_at'=>$now, ]); $n++; } echo "inserted $n solution rows\n"; echo "questions in scope with a linked solution now: ".DB::table('questions')->where($scope)->whereIn('id', function($q){ $q->select('question_id')->from('solutions'); })->count()."\n";