|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Database\Seeders; |
| 6 | + |
| 7 | +use App\Models\Article; |
| 8 | +use App\Models\Comment; |
| 9 | +use App\Models\User; |
| 10 | +use Illuminate\Database\Seeder; |
| 11 | + |
| 12 | +class ArticleCommentSeeder extends Seeder |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Run this seeder for API testing purpose only. |
| 16 | + * NOTE: DON'T RUN THIS IN PRODUCTION, this is for testing purposes only. |
| 17 | + */ |
| 18 | + public function run(): void |
| 19 | + { |
| 20 | + // Create 10 users for comments |
| 21 | + $users = User::factory(10)->create(); |
| 22 | + |
| 23 | + // Create 20 categories and 30 tags |
| 24 | + $categories = \App\Models\Category::factory(20)->create(); |
| 25 | + $tags = \App\Models\Tag::factory(30)->create(); |
| 26 | + |
| 27 | + // Create 100 articles |
| 28 | + $articles = Article::factory(100)->create(); |
| 29 | + |
| 30 | + foreach ($articles as $article) { |
| 31 | + // Attach 1-3 random categories to each article |
| 32 | + $article->categories()->attach($categories->random(rand(1, 3))->pluck('id')->toArray()); |
| 33 | + // Attach 2-5 random tags to each article |
| 34 | + $article->tags()->attach($tags->random(rand(2, 5))->pluck('id')->toArray()); |
| 35 | + |
| 36 | + // Create 10 top-level comments for each article |
| 37 | + $topComments = []; |
| 38 | + for ($i = 0; $i < 10; $i++) { |
| 39 | + $topComments[$i] = Comment::factory()->create([ |
| 40 | + 'article_id' => $article->id, |
| 41 | + 'user_id' => $users->random()->id, |
| 42 | + 'parent_comment_id' => null, |
| 43 | + ]); |
| 44 | + } |
| 45 | + // For each top-level comment, create 2 child comments (level 1) |
| 46 | + foreach ($topComments as $parentComment) { |
| 47 | + for ($j = 0; $j < 2; $j++) { |
| 48 | + $child = Comment::factory()->create([ |
| 49 | + 'article_id' => $article->id, |
| 50 | + 'user_id' => $users->random()->id, |
| 51 | + 'parent_comment_id' => $parentComment->id, |
| 52 | + ]); |
| 53 | + // For each child comment, create 2 more child comments (level 2) |
| 54 | + for ($k = 0; $k < 2; $k++) { |
| 55 | + Comment::factory()->create([ |
| 56 | + 'article_id' => $article->id, |
| 57 | + 'user_id' => $users->random()->id, |
| 58 | + 'parent_comment_id' => $child->id, |
| 59 | + ]); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments