😂Có 10 phần tử trong mảng lấy ngẫy nhiên 1 phần từ sao cho mỗ lần lấy ra phần từ khác nhau (ok)

<?php
namespace Database\Factories;
use Carbon\Traits\ToStringFormat;
use Illuminate\Database\Eloquent\Factories\Factory;
use Nette\Utils\Strings;
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\History>
 */
class HistoryFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array<string, mixed>
   */
  public function definition(): array
  {
    // Sử dụng static để mảng $userids được giữ nguyên trạng thái giữa các lần gọi hàm
    static $userids;
    // Chỉ khởi tạo và trộn mảng một lần duy nhất khi chạy Factory lần đầu
    if (!isset($userids)) {
      $userids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      shuffle($userids);
    }
    // Lấy (và xóa) phần tử cuối cùng ra khỏi mảng
    // array_pop sẽ trả về NULL nếu mảng rỗng
    $currentUserId = array_pop($userids);
    return [
      "user_id" => $currentUserId,
      "description" => "History 𝗢𝗻 ✅ " . (string) $this->faker->date() . ""
    ];
  }
}

Last updated