【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null?SQLSTATE [23000]:违反完整性约束:1048 列 'user_id' 不能为空?
【发布时间】:2022-01-23 04:15:51
【问题描述】:

我在尝试播种数据库时收到此错误。

Laravel 7.

博文模型

class BlogPost extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'user_id',
        'category_id',
        'excerpt',
        'content_raw',
        'content_html',
        'is_published',
        'published_at',
        'updated_at',
        'created_at',
    ];

    public function category()
    {
        return $this->belongsTo(BlogCategory::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

用户模型

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

用户迁移

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

BlogPost 迁移

        Schema::create('blog_posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('category_id');
            $table->foreignId('user_id')->constrained();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('excerpt')->nullable();
            $table->text('content_raw');
            $table->text('content_html');
            $table->boolean('is_published')->default(false)->index();
            $table->timestamp('published_at')->nullable();
            $table->foreign('category_id')->references('id')->on('blog_categories');
            $table->timestamps();
        });

用户播种器

class UserTableSeeder extends Seeder
{
    public function run()
    {
        $users = [
            [
                'name' => 'Author',
                'email' => 'seriiburduja@mail.ru',
                'password' => bcrypt('some1234')
            ],
            [
                'name' => 'Admin',
                'email' => 'seriiburduja@gmail.com',
                'password' => bcrypt('some1234')
            ]
        ];

        DB::table('users')->insert($users);
    }
}

博文工厂

$factory->define(BlogPost::class, function (Faker $faker) {
    $title = $faker->sentence(rand(3, 8), true);
    $text = $faker->realText(rand(1000, 4000));
    $isPublished = rand(1, 5) > 1;
    $createdAt = $faker->dateTimeBetween('-6 months', '-1 day');

    return [
        'category_id' => rand(1, 10),
        'user_id' => 1,
        'title' => $title,
        'slug' => Str::slug($title),
        'excerpt' => $faker->text(rand(100, 400)),
        'content_raw' => $text,
        'content_html' => $text,
        'is_published' => $isPublished,
        'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
        'created_at' => $createdAt,
        'updated_at' => $createdAt
    ];
});

数据库播种器

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserTableSeeder::class);
        $this->call(BlogCategorySeeder::class);
        factory(BlogPost::class, 1)->create();
    }
}

当我运行php artisan migrate:fresh --seed 时出现此错误。

表格用户和 blog_categories 种子成功,但 blog_categories 出现错误。

我不明白为什么。

字段 user_id 存在于 BlogPost 模型的 $fillable 中。

如果我更改 blog_posts 的迁移并为 user_id 添加一个可为空的,则种子工作,但 user_id 为空。但我不需要那个。

提前致谢。

【问题讨论】:

  • 在您的博文工厂中添加dd([/*return result*/ ]) 以确保它被正确点击并生成合理的数据。
  • @apokryfos 完成。 ``` $result = [ 'category_id' => rand(1, 10), 'user_id' => 1, 'title' => $title, 'slug' => Str::slug($title), ]; dd($结果); ``` And user_id ``` "category_id" => 4 "user_id" => 1 "title" => "Voluptatem vel blanditiis dignissimos eligendi culpa ratione molestias accusamus。" “蛞蝓”=>“voluptatem-vel-blanditiis-dignissimos-eligendi-culpa-ratione-molestias-accusamus”```

标签: laravel migration laravel-seeding


【解决方案1】:

在博客文章模型中

将用户关系更改为

public function owner()
{
    return $this->belongsTo(User::class);
}

在用户模型中 添加此关系

public function blogposts()
{
    return $this->hasMany(BlogPost::class);
}

在 Database Seeder 中不要使用 UserSeeder 直接在 DatabaseSeeder 中创建用户

public function run()
{
    $user = User::create([
        'name' => "Your name",
        'email' => "youremail@gmail.com",
        'password' => Hash::make('YourPassword')
    ]);

    $this->call(BlogCategorySeeder::class);
    
    $user->blogposts()->saveMany(BlogPost::factory(1));
}

在 BlogPost Factory 中删除 user_id

return [
    'category_id' => rand(1, 10),
    'title' => $title,
    'slug' => Str::slug($title),
    'excerpt' => $faker->text(rand(100, 400)),
    'content_raw' => $text,
    'content_html' => $text,
    'is_published' => $isPublished,
    'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
    'created_at' => $createdAt,
    'updated_at' => $createdAt
];

fillable在您使用 Seeder 插入数据时不是必需的。

如果您想在数据库中插入每一列,那么您可以使用与 fillable 相对的 guarded 属性。

【讨论】:

  • 感谢回答。昨天我有点不舒服,无法回答。尝试播种数据时出现错误。 ``` 调用未定义的方法 App\BlogPost::factory() ```
  • 进行此更改“使用 App\Models\BlogPost”; 然后重试
猜你喜欢
  • 2020-10-26
  • 2021-02-01
  • 2019-11-20
  • 2021-08-16
  • 2019-10-06
  • 2020-10-25
  • 2017-02-28
  • 2017-04-15
  • 2017-12-26
相关资源
最近更新 更多