Can't seed the database in Laravel

泪湿孤枕 提交于 2021-02-05 12:16:04

问题


I'm currently seed my database in Laravel, migrations works properly and I am able to see the tables in SQL workbench. But when I run the command php artisan db:seed nothing happens.

I can't find the cause of it. I'm pretty new to Laravel.

DB name is 'Laravel', the table name is 'books'.

Seeder Code:

 DB::table('books')->insert($books = [
        ['name' => 'Harry Potter', 'writer_name' => 'J.K. Rowling', 'isbn' => '9780739360385'],
        ['name' => 'Game of Thrones', 'writer_name' => 'George R.R. Martin', 'isbn' => '9780739308684'],
        ['name' => 'Harry Potter', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528807'],
        ['name' => 'The Lord of The Rings', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780563528883'],
        ['name' => 'The Silmarillion', 'writer_name' => 'J.R.R. Tolkien', 'isbn' => '9780007120604'],
        ['name' => 'Animal Farm', 'writer_name' => 'George Orwell', 'isbn' => '9780140862515'],
        ['name' => 'It', 'writer_name' => 'Stephan King', 'isbn' => '9781441738707'],
        ['name' => 'The Art of Deception', 'writer_name' => 'Kevin Mitnick', 'isbn' => '9780470249321'],
    ]);
    foreach ($books as $book) {
        Book::create($book);
    }

Migration Code:

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('writer_name');
        $table->string('image')->nullable();
        $table->string('isbn')->unique();
        $table->timestamps();
    });

回答1:


Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Pass the name of the seeder class you wish to run:

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
        CommentSeeder::class,
    ]);
}



回答2:


You can also specify which seeder file to run by command php artisan db:seed --class=yourseedername Also in you seeder code you are inserting same data twice one by DB query and another from Book model. So you are duplicating same data twice. I believe an error should be thrown as column violation saying integrity constraint violation as isbn for books are unique.



来源:https://stackoverflow.com/questions/63340636/cant-seed-the-database-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!