我需要运行工厂 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 中,我收到以下消息:
以下是 IDE 中的错误捕获:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在我看来,你想为中间表播种。播种时可以使用一些方法,其中之一是
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();