Skip to content
Advertisement

: SQLSTATE[HY000]: General error: 1364 Field

I got this error, when I added columns

$table->unsignedBigInteger('user_id'); #added 
$table->foreign('user_id')->references('id')->on('users'); #added

on create_posts_table.php. I was creating UserSeederTable but it doesn’t work. And why can’t I create PostSeedertable now? Before the columns adding, there were no errors. Please help.

config/database.php
'strict' => false, (was true → false) still errors.
 IlluminateDatabaseQueryException  : SQLSTATE[HY000]: General error: 1364 Field 
   IlluminateDatabaseQueryException  : SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`created_at`, `updated_at`, `subject`, `message`, `name`) values (2013-02-13 02:11:00, 1972-03-04 01:34:26, ~~~~~~~~~~~~))

laravel-app/app/Post.php

use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    /**
     * 投稿データを所有するユーザを取得
     */
    public function user()
    {
     return $this->belongsTo('AppUser');
    }
    
     // 
     protected $fillable = [
        'name',
        'subject',
        'message', 
        'user_id',
        #'category_id'
    ];

migrations/2021_03_10_101736_create_posts_table.php


use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
            $table->string('is_deleted', 4)->default('0');
            #$table->integer('category_id');
            $table->string('subject');
            $table->text('message');
            $table->string('name');
            $table->unsignedBigInteger('user_id'); #added 
            $table->foreign('user_id')->references('id')->on('users'); #added 
        });
    }

seeds/PostsTableSeeder.php

use IlluminateDatabaseSeeder;

class PostsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(AppPost::class, 50)
            ->create()
            ->each(function ($post) {
                $comments = factory(AppComment::class, 2)->make();
                $post->comments()->saveMany($comments);
            }
        );
    }
}

factories/UserFactory.php
$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});



$ php artisan migrate:refresh
Dropped all tables successfully.
Migration table created successfully.
$  php artisan db:seed
Seeding: PostsTableSeeder

Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value")
      /var/www/html/laravel-app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /var/www/html/laravel-app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
end

Advertisement

Answer

It’s telling you that user_id cannot be null and it’s currently null. This typically means user_id isn’t being filled by the factory.

You have 3 options:

  • Update your post factory to include user_id

OR

  • You can bypass this by changing the migration to allow user_id to be nullable.

OR

  • Setting a default value for user_id in the migration
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement