Laravel 9数据库\工厂\附属工厂::公司():参数#1($company)的类型必须为Database\Factories\Company,并给定数组

wlzqhblo  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(111)

我正在尝试将Affiliate与Laravel 9项目中附属工厂中的UserCompany关联。
每次运行seeder时,都会抛出以下错误:
数据库\工厂\附属工厂::公司():参数#1($company)的类型必须为Database\Factories\Company,并给定数组
我有意地需要传递用户和公司id,因为我需要在我的附属工厂的定义中设置它们,以便正确地分配它们。
如何解决此错误我。
我的AffiliateFactory

<?php

namespace Database\Factories;

use App\Models\Affiliate;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Carbon\Carbon;

class AffiliateFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Affiliate::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $affiliate = 'aff'.Str::random(4);
        $apiHash = Str::random(32);

        return [
            'aff_id' => 'aff'.Str::random(4),
            'description' => rand(0, 100) > 50 ? $this->faker->sentence() : null,
            'api_key' => md5($affiliate.$apiHash),
            'api_hash' => $apiHash,
            'allow_submission' => $this->faker->boolean(),
            'is_favourited' => $this->faker->boolean(),
            'is_default' => $this->faker->boolean(),
            'is_enabled' => true,
            'last_used_at' => Carbon::now()->subHours(rand(0, 72))->subMinutes(rand(0, 60))
        ];
    }

    /**
     * Set the company for this factory
     *
     * @param Company $company
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    public function forCompany(Company $company)
    {
        return $this->state(function (array $attributes) use ($company) {
            return [
                'user_id' => $company->user_id,
                'company_id' => $company->id,
            ];
        });
    }
}

呼叫方式:

// create our users
$users = User::factory(10)->create();

// assign one company to each user
foreach ($users as $user) {
    Company::factory()->for($user)->count(1)->create();
}

$companies = Company::all();

foreach ($companies as $company) {
    Affiliate::factory(50)->forCompany([
        'user_id' => $company->user_id,
        'company_id' => $company->id
    ])->create();
}
mwngjboj

mwngjboj1#

您没有将模型App\Models\Company包含在AffiliateFactory中,这就是它在类AffiliateFactory的名称空间中搜索Company类的原因。
只要把你的模型放在顶部,它就应该起作用了。

use App\Models\Company;

// now uses App\Models\Company instead of Database\Factories\Company;
public function forCompany(Company $company) {
 ...
}

相关问题