Quay lại

Seeding model rows dựa trên user input trong Laravel Chuyên mục PHP và Laravel    2023-09-09    1k Lượt xem    7 Lượt thích    comment-3 Created with Sketch Beta. 0 Bình luận

Seeding model rows dựa trên user input trong Laravel

Thông thường, sẽ rất hữu ích nếu bạn có thể chọn số lượng rows model dựa trên thông tin đầu vào của người dùng. Tức là bạn không hardcode số lượng rows mà seeder sẽ tạo ra. Người dùng sẽ chuyển số đó trong khi chạy seeder.

Ví dụ: Giả sử chúng ta có một factory BookFactory.php trong database/factories trông giống như sau.

<?php

namespace Database\Factories;

use App\Models\Book;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class BookFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Book::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'author' => $this->faker->name,
            'published' => 1
        ];
    }
}

Và bây giờ, nếu bạn muốn sử dụng factory này trong BookSeeder.php với số rows do người dùng cung cấp sẽ được tạo, bạn có thể làm như sau:

<?php

namespace Database\Seeders;

use App\Models\Book;
use Illuminate\Database\Seeder;

class BookSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $count = $this->command->ask(
            'How many books you want to create?', 
            10
        );

        Book::factory((int)$count)->create();
    }
}

Bây giờ, khi bạn chạy seeder bằng cách sử dụng php Artisan db:seed --class=BookSeeder, bạn sẽ được nhắc với câu hỏi “How many books you want to create?”. Sau đó, bạn có thể cung cấp số rows bạn muốn seed hoặc chỉ cần nhấn enter, thao tác này sẽ tạo 10 hàng theo mặc định.

Đây là cách nó trông như thế nào.

Bình luận (0)

Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough

Bài viết liên quan

Learning English Everyday