当在我的CategoryFactory中执行自引用关系时,我得到以下错误'The process has been signaled with signal“11”.'。例如,我有以下代码:
CategoryTest.php
<?php
namespace Tests\Unit\Models\Categories;
use App\Models\Category;
use Tests\TestCase;
class CategoryTest extends TestCase
{
/**
* A basic unit test example.
*
* @return void
*/
public function test_it_has_children()
{
$category = Category::factory()
->has(Category::factory()->count(3), 'children')
->create();
$this->assertInstanceOf(Category::class, $category->children->first());
}
}
看起来这就是错误的来源。我现在确定这是否是引用hasMany关系的正确方法。
CategoryFactory.php
<?php
namespace Database\Factories;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class CategoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Category::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $name = $this->faker->unique()->name,
'slug' => Str::of($name)->slug('-'),
'parent_id' => Category::factory() // This seems to be causing the error
];
}
}
Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'order'
];
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
}
我不知道这个错误可能指向什么
3条答案
按热度按时间lnxxn5zx1#
关于这条线,你认为这似乎是造成错误。我认为这个错误可能是由递归或类似的东西引起的。尝试将其更改为:
u3r8eeie2#
每次你调用
Category::factory()->create()
,它都会通过调用Category::factory()->create()
在内部为它创建一个父级,所以这是一个永恒的循环。您的子创建逻辑是正确的,并且它们被分配了正确的父。
您可以通过在使用顶级类别时为它分配一个空父级来解决这个问题
最好在工厂中更改它,以便自动创建的父类别是顶级类别。
顺便说一句,如果只提供name参数,工厂的行为会很奇怪。就像子弹代表另一个名字一样
ymdaylpp3#
我必须将RefreshDatabase特性添加到我的测试类中