将值作为参数发送到工厂类
P粉378890106
P粉378890106 2024-01-03 14:42:16
0
1
432

我需要运行工厂 50 次,因此在 DatabseSeeder 内:

public function run()
{
    for($i=1;$i<=50;$i++){
       (new CategoryQuestionFactory($i))->create();
    }
}

正如您所看到的,我尝试将名为 $i 的变量作为参数传递给 CategoryQuestionFactory 类。

然后在这家工厂,我尝试了这个:

class CategoryQuestionFactory extends Factory
{
    protected $counter;

    public function __construct($c)
    {
        $this->counter = $c;
    }
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        $question = Question::find($this->counter);

        return [
            'category_id' => $this->faker->numberBetween(1,22),
            'question_id' => $question->id
        ];
    }
}

但是当我在终端运行 php artisan db:seed 时,出现此错误:

在 null 上调用成员函数 pipeline()

在 C:xampphtdocsforumrootvendorlaravelframeworksrcIlluminateDatabaseEloquentFactoriesFactory.php:429

那么这里出了什么问题呢?如何正确地将值作为参数发送给工厂类?

此外,在该工厂的 __construct 方法的 IDE 中,我收到以下消息:


更新#1:

以下是 IDE 中的错误捕获:

P粉378890106
P粉378890106

全部回复(1)
P粉447785031

在我看来,你想为中间表播种。播种时可以使用一些方法,其中之一是 has(),这是我经常使用的方法。

/**
* will create a one question and 3 category then create a data in the intermediate table. 
* expected data : 
* question_id | category_id
*     1            1
*     1            2
*     1            3
*/
Question::factory()->has(
    Category::factory()->count(3)
)->create();

假设您想要创建 100 个问题和 5 个类别

/**
* will create a 100 question and 5 category then create a data in the intermediate table. 
* expected data : 
* question_id | category_id
*     1            1
*     1            2
*     1            3
*     1            4
*     1            5
*     2            1
*     2            2
*     2            3
*     2            4
*     2            5
* until the 100th question will have a 5 categories
*/
Question::factory(100)->has(
    Category::factory()->count(5)
)->create();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!