首页 > 解决方案 > Laravel 8 - 当工厂中的自引用关系时,该过程已用信号“11”发出信号

问题描述

我收到以下错误“进程已通过信号“11”发出信号。” 在我的 CategoryFactory 中执行自引用关系时。例如我有以下代码:

分类测试.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 关系的正确方法。

分类工厂.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
        ];
    }
}

分类.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');
    }
}

我不知道这个错误可能指向什么

标签: phplaravelphpunitlaravel-8

解决方案


关于这条线,您认为这似乎导致错误。我认为错误可能是由递归或类似的东西引起的。尝试将其更改为:

'parent_id' => function () {
   return factory(Category::class)->create()->id;
}

推荐阅读