我正在为这个项目做测试覆盖,现在我需要创建用户模型工厂。
我使用工匠命令创建了这个工厂:
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 = []
.
没用。项目中的其他工厂工作正常
试试这个
'username' => $this->faker->unique()->userName(),
userName()
代替userName