我收到错误 array_merge 预期参数 2 在 laravel 8 工厂中?

I got error array_merge Expected parameter 2 to be in laravel 8 factory?

在 Laravel 8.12 运行ning factory from controller 我得到错误:

[2021-01-12 16:42:10] local.ERROR: array_merge(): Expected parameter 2 to be an array, int given {"exception":"[object] (ErrorException(code: 0): array_merge(): Expected parameter 2 to be an array, int given at /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:381)
[stacktrace]
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError()
#1 /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php(381): array_merge()
#2 [internal function]: Illuminate\Database\Eloquent\Factories\Factory->Illuminate\Database\Eloquent\Factories\{closure}()
#3 /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Collections/Collection.php(884): array_reduce()

... 在控制器中我 运行 :

Ad::addDummyData();

在app/Models/Ad.php:

public 静态函数 addDummyData() {

$ads = Ad::factory()->create(10); // POINTS TO THIS LINE
\Log::info(  varDump($ads, ' -1 addDummyData() $ads::') );

}

在database/factories/AdFactory.php :

<?php

namespace Database\Factories;

use Config;
use App\Models\Ad;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class AdFactory extends Factory
{
    protected $model = Ad::class;

    public function definition()
    {
        $text= $this->faker->text;
        $slugValue = SlugService::createSlug(Ad::class, 'slug', $text);

        \Log::info(  varDump($slugValue, ' -1 $slugValue::') );
        return [
            'title' => $text,
            'ad_token' => $text,
            'slug' => $slugValue,
            'phone_display' => (rand(1, 3) == 1),
            'has_locations' => (rand(1, 4) == 1),
            'status' => 'A', // password
            'price' => mt_rand(10, 500),
            'ad_type' => (rand(1, 2) == 1 ? 'B' : 'S'),
            'expire_date' => $this->faker->dateTimeThisMonth('now', Config::get('app.timezone'))->format('Y-m-d H:i:s'),
            'description' => $this->faker->paragraphs(rand(1, 4), true),
            'creator_id' => rand(1, 5),
        ];
    }
}

在错误描述中我没有提及database/factories/AdFactory.php.

为什么会出错,如何解决?

谢谢!

使用create方法时必须传递属性数组。参数是覆盖工厂的默认模型属性。

这是文档中的示例:

$user = User::factory()->create([
    'name' => 'Abigail',
]);

如果要创建模型10次,需要使用count方法:

Ad::factory()->count(10)->create();