0

早上好,

我无法将数据从我的工厂发送到我的数据库。

SQLSTATE[HY000]: General error: 1364 Field 'genre_id' doesn't have a default value (SQL: insert into `books` (`isbn`, `title`, `publish_date`, `updated_at`, `created_at`) values (4243421897, Prof., 1992-09-08 00:57:41, 2020-03-10 15:02:36, 2020-03-10 15:02:36))

我不知道在我的迁移中是否必须指定我的 foreign_keys 没有默认值......

这些是我的文件:

create_books_table.php

 public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->id('isbn');
            $table->string('title' , 100);
            $table->text('cover')->nullable();
            $table->date('publish_date');
            $table->bigInteger('genre_id')->unsigned();
            $table->bigInteger('author_id')->unsigned();
            $table->bigInteger('user_id')->unsigned();
            $table->timestamps();

            $table->foreign('genre_id')
                ->references('id')->on('Genres')
                ->onUpdate('cascade')
                ->onDelete('cascade');

            $table->foreign('author_id')
                ->references('id')->on('Authors')
                ->onUpdate('cascade')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')->on('Readers')
                ->onUpdate('cascade')
                ->onDelete('cascade');
        });
    }

BookFactory.php

$factory->define(Book::class, function (Faker $faker) {
    return [
        'isbn' => $faker->isbn10,
        'title' => $faker->title,
        'publish_date' => $faker->dateTime()
    ];
});

我还没有在我的 web.php 中创建一个“路由”,所以我也没有完成 CRUD,我什至没有修改我的刀片,但我现在只想设置我的整个数据库。但我想知道这是否不是问题所在。

这是我数据库中的示意图: https ://imgur.com/a/8Txn7x2 (我还不允许上传图片。)

(我在编码学校)

谢谢!

4

1 回答 1

2

您已将genre_id列定义为必需的或始终包含值。但是,您的插入查询不包含genre_id值。在这种情况下,MySQL 将回退到为该列配置一个默认值,但您还没有定义一个。

默认值对于像 之类的外键样式列没有多大意义genre_id,除非您有特定理由指定在未明确提供时使用的默认 ID。

更好的选择是制作 column nullable,或者能够使用NULL值而不是现有 ID。将迁移中的行修改为:

$table->bigInteger('genre_id')->unsigned()->nullable();

当外键列是nullable时,它不会对该NULL值执行任何断言,只会执行非空值。

于 2020-03-10T15:57:46.940 回答