make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); $rows = App\Models\ArtworkComment::where('artwork_id', 10) ->whereNotNull('parent_id') ->select('id', 'parent_id', 'content') ->orderByDesc('id') ->limit(15) ->get(); foreach ($rows as $r) { echo "id={$r->id} parent_id={$r->parent_id} content=" . mb_substr($r->content, 0, 40) . PHP_EOL; } echo "\n--- Tree test (recursive eager-load) ---\n"; $top = App\Models\ArtworkComment::with(['approvedReplies']) ->where('id', 175742) ->get(); function printTree($comments, $indent = 0) { foreach ($comments as $c) { $prefix = str_repeat(' ', $indent); $replies = $c->relationLoaded('approvedReplies') ? $c->approvedReplies : collect(); echo "{$prefix}[{$c->id}] " . mb_substr($c->content, 0, 40) . " ({$replies->count()} replies)\n"; if ($replies->count()) { printTree($replies, $indent + 1); } } } printTree($top);