如何在覆盖工厂参数时在 Laravel 的种子文件中声明 $faker?

How to declare $faker in the seed file in Laravel when overriding for argument to factory?

我正在尝试创建多个种子模型,例如带有样本参数的 seedt1、seedt2、seedt3。

我知道工厂状态,我不想使用它,我想尽可能保持我的工厂模型最小和干净。

我有我的模型工厂:

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\User;
use App\Client;
use App\Query;
use App\Task;
use Faker\Generator as Faker;

////////// Users factory //////////
$factory->define('App\User', function (Faker $faker) {
    $faker->locale = 'fr_FR';
    return [
        'full_name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('secret'),
        'remember_token' => Str::random(10),
        'objective' => '0',
        'role_id' =>1,
        'isActive' => '1',
        'img_path' =>'user-lg.jpg',
    ];
});

////////// Clients factory //////////
$factory->define('App\Client', function ($faker) {
    $faker->locale = 'fr_FR';
    return [
        'name' => $faker->company,
        'legalname' => $faker->name,
        'legalname2' => $faker->name,
        'legalname3' => $faker->name,
        'email' => $faker->email,
        'address' => $faker->address,
        'country' => $faker->country,
        'website' => $faker->domainName,
        'telephone' => $faker->phoneNumber,
        'telephone2' => $faker->phoneNumber,
        'fax' => $faker->PhoneNumber,
        'other1' => $faker->email,
        'other2' => $faker->email,
        'other3' => $faker->email,
        'foundeddate' => $faker->dateTimeThisDecade,
        'crmregistered' => $faker->dateTimeThisYear,
        'comments' => $faker->realText($maxNbChars = 300, $indexSize = 2),
        'insurancenumber' => $faker->numberBetween($min = 80000, $max = 150000),
        'data1' => $faker->boolean($chanceOfGettingTrue = 50),
        'data2' => $faker->boolean($chanceOfGettingTrue = 50),
        'type_id' => $faker->numberBetween($min = 1, $max = 2),
        'isActive' => '1',
        'user_id' => $faker->numberBetween($min = 3, $max = 15),
        'img_path' =>'imageUrl($width, $height, \'cats\')',
    ];
});
////////// Queries factory //////////
$factory->define('App\Query', function ($faker) {
    $faker->locale = 'fr_FR';
    return [
        'guests_no' => $faker->numberBetween($min = 50, $max = 500),
        'days_no' => $faker->numberBetween($min = 3, $max = 7),
        'value' => $faker->ean8,
        'arrival_date' => $faker->dateTimeInInterval($startDate = '+1 years', $interval = '+ 14 days', $timezone = null),
        'departure_date' => $faker->dateTimeInInterval($startDate = '+1 years', $interval = '+ 21 days', $timezone = null),
        'file_name' => $faker->numerify('dossier ######'),
        'file_number' => $faker->ean8,
        'facture_number' => $faker->creditCardNumber,
        'guide' => $faker->boolean($chanceOfGettingTrue = 50),
        'rentacar' => $faker->boolean($chanceOfGettingTrue = 50),
        'aerial' => $faker->boolean($chanceOfGettingTrue = 50),
        'user_id' => $faker->numberBetween($min = 3, $max = 15),
        'client_id' => $faker->numberBetween($min = 1, $max = 1000),
        'transport_type_id' => $faker->numberBetween($min = 1, $max = 3),
        'created_at' => $faker->dateTimeThisYear,
        'payment_status_id' => $faker->numberBetween($min = 1, $max = 3),
        'query_status_id' => $faker->numberBetween($min = 1, $max = 7),
        'query_type_id' => $faker->numberBetween($min = 1, $max = 3),
        'isActive' => '1',
        'notified' => $faker->boolean($chanceOfGettingTrue = 50),
    ];
});
////////// Task factory //////////
$factory->define('App\Task', function ($faker) {
    $faker->locale = 'fr_FR';
    return [
        'text' => $faker->realText($maxNbChars = 300, $indexSize = 2),
        'name' => $faker->name,
        'status' => $faker->ean8,
        'user_id' => $faker->numberBetween($min = 3, $max = 15),
        'query_id' => $faker->numberBetween($min = 1, $max = 500),
        'isActive' => '1',
        'query_status_id' => $faker->numberBetween($min = 1, $max = 7),
    ];
});
////////// State sample factory //////////
/*$factory->state(App\User::class, 'delinquent', function ($faker) {
    return [
        'account_status' => 'delinquent',
    ];
});*/

和我的种子文件:

<?php

use Illuminate\Database\Seeder;

class sampleT1 extends Seeder
{

    public function run()
    {

        factory('App\User', 1)->create(['role_id' =>'2',]); //1 financial user id 2
        factory('App\User', 3)->create(['role_id' =>'4',]); //3 managers id 3-5
        factory('App\User', 5)->create(); //10 users id 6-10
        factory('App\Client', 300)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10),]); //300 clients
        factory('App\Query', 1000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'client_id' => $faker->numberBetween($min = 1, $max = 300),]); //300 queries
        factory('App\Task', 5000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'query_id' => $faker->numberBetween($min = 1, $max = 250),]); //5000 tasks
        //factory('App\User', 50)->states('premium', 'delinquent')->create();

    }
}

当我 运行 我的种子时:php artisan db:seed --class=sampleT1

我得到结果:

deployer@debdaddytp:/var/www/mice$ php artisan db:seed --class=sampleT1

   ErrorException 

  Undefined variable: faker

  at database/seeds/sampleT1.php:20

显然 faker 的变量不是从模型工厂继承的,我应该如何在我的种子中声明它才能工作?

Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

$faker = Faker\Factory::create();

并且应该可以正常工作。 source.

我认为你需要像这样使用它

factory('App\Client', 300)->create()->each(function($client) {
    $user = App\User::find(rand(3, 10));

    //That if you have set a  Many to many relationship (which I honestly doubt of it but just showing for the exemple)
    $client->users()->attach($user);

    //That if you have set a  belongsTo relationship
    $client->user()->associate($user);

    //That if relationship is not set
    $client->user_id = $user->id;

}

保持事情的一致性总是一个好主意,所以我建议按照 Factory class 的方式来做。您的播种机将如下所示:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Faker\Generator;
use Illuminate\Container\Container;

class MySeeder extends Seeder
{
    /**
     * The current Faker instance.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Create a new seeder instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->faker = $this->withFaker();
    }

    /**
     * Get a new Faker instance.
     *
     * @return \Faker\Generator
     */
    protected function withFaker()
    {
        return Container::getInstance()->make(Generator::class);
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // ...
    }
}
...
use Faker\Factory as Faker;
...

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->faker = Faker::create();
        $number = $this->faker->randomDigit();
    }
}

我在 Laravel 9.x.

中使用它
// database/seeders/DatabaseSeeder.php

namespace Database\Seeders;

use Faker\Generator;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $faker = app(Generator::class);

        // use 
        // $faker->text()
        // $faker->dateTimeThisYear()
    }
}