简体   繁体   中英

How to pass arguments from seeders to factories?

I want to pass arguments ['site_id' => $site->id] to SiteMessage factory:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\SiteMessage;
use App\Models\Site;

class SitesMessagesTableSeeder extends Seeder
{
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
        Site::chunk(200, function ($sites) {
            foreach ($sites as $site) {
                SiteMessage::factory()->count(rand(2, 6))->create(['site_id' => $site->id]);
            }
        });
    }
}

How can I get those argument in my SiteMessage factory class?

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\SiteMessage;
use App\Models\Site;
use App\Models\Integration;

class SiteMessageFactory extends Factory
{
   
    protected $model = SiteMessage::class;

    public function definition()
    {
        return [
             **// Soliution: remove line below, it will be overridden automaticaly. \\**
            'site_id'       => $arguments['site_id'], // Neet to use Id that I passed from seeder. 
            'integration_id'=> Integration::inRandomOrder()->first()->id,
            'type'          => rand(0,1) ? 'EMAIL' : 'SMS',
            'title'         => $this->faker->text($maxNbChars = 12),
            'description'   => $this->faker->sentence,
            'message'       => $this->faker->sentence,
            'enabled'       => 1,
            'created_at'    => now(),
            'updated_at'    => now(),
        ];
    }
}

At older Laravel factory version I could pass them in callback like so:

$factory->define(SiteMessage::class, function (Faker $faker, array $arguments = []) {
//
});

but don't know how to achieve it with new Class factories. Any help would be very appreciated :)

As you can see in the laravel documentation aboutpersisting models with factories , when you type:

SiteMessage::factory()->count(rand(2, 6))->create(['site_id' => $site->id]);

The site_id attribute from SiteMessage factory will be overrided by the $site->id you are specifying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM