: SQLSTATE[HY000]: General error: 1364 Field



我得到这个错误,当我添加列

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

oncreate_posts_table.php。我在创建UserSeederTable,但它不起作用。为什么我现在不能创建PostSeedertable呢?在添加列之前,没有错误。请帮助。

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

它告诉你user_id不能为空,它目前为空。这通常意味着user_id没有被工厂填充。

你有3个选项:

  • 更新你的post factory以包含user_id

  • 你可以通过改变迁移允许user_id为空来绕过这个。

  • 设置迁移中user_id的默认值

相关内容

  • 没有找到相关文章

最新更新