我正在为这个项目进行测试覆盖,现在我需要创建一个用户模型工厂。
我使用artisan命令创建了这个工厂: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 = []
。
没用的项目中的其他工厂工作正常
UPD 1:User::create()
方法得到了相同的错误。但下一个代码可以工作:
$user = new User();
$user->username = 'Test';
$user->password = Hash::make('test');
$user->name = 'Test';
$user->email = 'test@test.com';
$user->save();
1条答案
按热度按时间gab6jxml1#
试试这个
'username' => $this->faker->unique()->userName(),
userName()
而不是userName