无法在 Laravel 中为数据库设定种子



我目前正在Laravel中为数据库播种,迁移工作正常,并且我能够在SQL工作台中查看表。但是当我运行命令php artisan db:seed时,什么也没发生。

我找不到原因。我对拉拉威尔很陌生。

DB名称为"Laravel",表名称为"books"。

播种机代码:

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);
}

迁移代码:

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();
});

DatabaseSeeder类中,可以使用call方法来执行其他种子类。使用call方法可以将数据库种子划分为多个文件,这样就不会有一个种子类变得过大。传递要运行的种子程序类的名称:

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

您还可以通过命令php artisan db:seed --class=yourseedername指定要运行的种子程序文件同样,在种子代码中,两次插入相同的数据,一次是通过DB查询,另一次是从Book模型。所以你们要重复两次相同的数据。我认为应该将一个错误作为列冲突抛出,称图书的isbn的完整性约束冲突是唯一的。

最新更新