Good morning,
I can't send data from my factory to my database.
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))
I don't know if in my migrations I have to specify that my foreign_keys don't have default values...
These are my files:
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()
];
});
I haven't yet created a 'Route' in my web.php so I haven't done the CRUD too, I haven't even modified my blades but I just want to set up my whole database for the moment. But I wonder if that's not the problem.
Here's a schematic from my database : https://imgur.com/a/8Txn7x2 (I'm not allowed to upload images yet. )
(i'm in coding school)
Thank you!
You've defined your genre_id
column as being required, or always containing a value. Your insert query, though, is not including a genre_id
value. In this case, MySQL will fall back to look for a default value configured for the column, but you haven't defined one.
A default value doesn't make much sense for a foreign key style column like genre_id
, unless you have a specific reason to specify a default ID to be used when one isn't explicitly provided.
The better choice would be to make the column nullable
, or able to use a NULL
value instead of an existing ID. Modify the line in your migration to:
$table->bigInteger('genre_id')->unsigned()->nullable();
When a foreign key column is nullable
, it won't perform any assertions for the NULL
value, only non-null values.