Wert als Parameter an Factory-Klasse senden
P粉378890106
P粉378890106 2024-01-03 14:42:16
0
1
433

Ich muss eine Fabrik leiten 50 次,因此在 DatabseSeeder Drinnen:

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

Wie Sie sehen können, habe ich versucht, die Klasse zu benennen $i 的变量作为参数传递给 CategoryQuestionFactory.

Dann habe ich in dieser Fabrik Folgendes versucht:

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
        ];
    }
}

Aber wenn ich php artisan db:seed im Terminal ausführe, erhalte ich diese Fehlermeldung:

Rufen Sie die Mitgliedsfunktion „pipeline()“ auf null auf

In C:xampphtdocsforumrootvendorlaravelframeworksrcIlluminateDatabaseEloquentFactoriesFactory.php:429

Was ist hier also das Problem? Wie sende ich Werte korrekt als Parameter an Factory-Klassen?

Außerdem erhalte ich in der IDE der __construct-Methode der Fabrik die folgende Meldung:


UPDATE #1:

Das Folgende ist die Fehlererfassung in der IDE:

P粉378890106
P粉378890106

Antworte allen(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();
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!