我刚刚创建了一个工厂,以便进行一些试验:
CategoryFactory.php
<?php
namespace DatabaseFactories;
use IlluminateDatabaseEloquentFactoriesFactory;
/**
* @extends IlluminateDatabaseEloquentFactoriesFactory<AppModelsCategory>
*/
class CategoryFactory extends Factory
{
/**
* Define the model s default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
//
company_id => 1,
name => fake()->name(),
parent_id => null
];
}
}
并在模型中添加:
类别.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use AppScopesCompanyScope;
class Category extends Model
{
//
use SoftDeletes, HasFactory;
protected $fillable = [
company_id ,
name ,
parent_id
];
public function __construct() {
parent::__construct();
if(isset(auth()->user()->company_id)) {
$this->attributes[ company_id ] = auth()->user()->company_id;
}
}
protected static function boot()
{
parent::boot();
static::addGlobalScope(new CompanyScope);
}
My test file looks like this:
public function test_category_edit_can_be_redered(): void
{
$user = User::factory()->create();
$category = Category::factory()->create();
$response = $this->actingAs($user)->get( /devices/categories/1/edit );
$response->assertStatus(200);
}
但是,当我尝试进行测试时,我发现以下错误:
General error: 1364 Field company_id doesn t have a default value (Connection: mysql, SQL: insert into `categories` (`updated_at`, `created_at`) values (2023-08-08 01:55:43, 2023-08-08 01:55:43))
它认为工厂的定义不适用于制造方法...... 任何想法,我是错做的?