【问题标题】:I got error array_merge Expected parameter 2 to be in laravel 8 factory?我收到错误 array_merge 预期参数 2 在 laravel 8 工厂?
【发布时间】:2021-04-17 13:07:14
【问题描述】:

在从控制器运行的 Laravel 8.12 工厂中出现错误:

[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 中:

公共静态函数 addDummyData() {

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

}

在数据库/工厂/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。

为什么会出错以及如何修复?

谢谢!

【问题讨论】:

    标签: laravel laravel-factory


    【解决方案1】:

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

    这是文档中的一个示例:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多