数组工厂 Laravel 上的随机选择值

问题描述 投票:0回答:4

我进行了用户迁移:

$table->enum('type',['seller','buyer'])->default('seller');

我想在使用ModelFactory时如何获得随机值卖家或买家?

$factory->define(App\User::class, function (Faker\Generator $faker) {

    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => ???,
    ];
});
laravel-5
4个回答
150
投票

利用

randomElement
方法

'type' => $faker->randomElement(['seller', 'buyer']),

11
投票

Laravel 版本 >= 5.6

use Illuminate\Support\Arr;

$array = [1, 2, 3, 4, 5];

$random = Arr::random($array);

// 4 - (retrieved randomly)

"type" => Arr::random($array);

5
投票

以防万一有人正在使用较新版本的 Laravel 和 PHP 寻找此问题的答案,您可以在 PHP 中使用

enum
,如下所示:

<?php

namespace App\Enums;

enum UserTypeEnum: string
{
    case SELLER = 'seller';
    case BUYER = 'buyer';
}

然后你的工厂将如下所示:

<?php

namespace Database\Factories;

use App\Enums\UserTypeEnum;
use Illuminate\Database\Eloquent\Factories\Factory;

class TaskFactory extends Factory
{
    public function definition()
    {
        return [
            'firstName' => fake()->firstName,
            'lastName' => fake()->lastName,
            'username' => fake()->unique()->username,
            'email' => fake()->unique()->safeEmail,
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password,
            'bio' => fake()->sentence(3, true),
            'type' => fake()->randomElement(UserTypeEnum::cases()),
        ];
    }
}

此外,如果您的

type
列是
nullable
,您也可以像
type
一样拥有您的播种机
fake()->randomElement([...UserTypeEnum::cases(), null])


0
投票

或者在另一种情况下也可能是

<?php

namespace Database\Factories;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Category>
 */
class CategoryFactory extends Factory
{

    public static $counter = 0;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {

        $arr_of_categories = ["Ui kits", "Components", "Templates"];
        $category_name = $arr_of_categories[$this::$counter % count($arr_of_categories)];
        $this::$counter += 1;
        return [
            //
            "name"=> $category_name,
            "slug"=> Str::slug($category_name),
        ];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.