Laravel 8 - 用户工厂错误 - `字段'用户名'没有默认值`

问题描述 投票:0回答:1

我正在为这个项目做测试覆盖,现在我需要创建用户模型工厂。

我使用工匠命令创建了这个工厂:

php artisan make:factory UserFactory

通话后

User::factory()->create();
我得到下一个错误:

SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into `admin_users` (`updated_at`, `created_at`) values (2023-01-01 10:00:00, 2023-01-01 10:00:00))

工厂代码:

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    public function definition(): array
    {
        return [
            'username' => $this->faker->unique()->userName,
            'password' => bcrypt('password'),
            'name' => $this->faker->name,
            'avatar' => $this->faker->imageUrl(),
            'email' => $this->faker->unique()->safeEmail
        ];
    }
}

用户模型代码:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class User extends Model implements AuthenticatableContract
{
    use Authenticatable, HasFactory;

    ...

    protected $fillable = [
        'username',
        'password',
        'name',
        'email',
        'avatar'
    ];

    ...
}

我试图将受保护的财产设置为

protected $guarded = []
.

没用。项目中的其他工厂工作正常

laravel unit-testing phpunit laravel-8 factory
1个回答
0
投票

试试这个

'username' => $this->faker->unique()->userName(),

userName()
代替
userName

© www.soinside.com 2019 - 2024. All rights reserved.