php 工厂中的Laravel访问关系模型

quhf5bfb  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(180)

我在Laravel 9项目中工作,正在使用模型工厂。我有User,它可以有一个Company
我需要将CompanyFactory的详细信息链接到User,例如名字和姓氏。user_id已经与LaravelMap。
这是我的尝试,或者说我认为我可以在CompanyFactory中做的事情:

$this->user->first_name

哪个是未定义的?
这是我的播种机:

// development seeders
User::factory(2)
    ->has(Affiliate::factory()->count(50))
    ->has(Company::factory()->count(1))
    ->has(Country::factory()->count(3))
    ->create();

我的CompanyFactory

<?php

namespace Database\Factories;

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

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        Log::debug('user', [
            'user' => $this->user,
        ]);

        return [
            'contact_first_name' => $user->first_name,
            'contact_last_name' => $user->last_name ? $user->last_name : null,
            'company_name' => $this->faker->company(),
            'address_1' => $this->faker->numberBetween(1, 16),
            'address_2' => 'Heatherbell Cottages',
            'address_3' => null,
            'town' => 'Wick',
            'county' => 'Caithness',
            'postcode' => 'KW14YT',
            'telephone_1' => $this->faker->regexify('07[1-57-9]{1}[0-9]{8}'),
            'telephone_2' => $this->faker->regexify('07[1-57-9]{1}[0-9]{8}'),
            'email' => $user->email,
            'bank_name' => $this->faker->word(),
            'bank_account_number' => $this->faker->numberBetween(11111111, 99999999),
            'bank_sort_code' => $this->faker->numberBetween(111111, 999999),
            'bank_iban' => $country ? $this->faker->iban($country->country_code) : null,
            'bank_swift' => '',
            'ccl_number' => null,
            'data_protection_number' => $this->faker->numberBetween(11111111, 99999999),
            'currency' => $country ? $country->currency_code : 'GBP',
            'notes' => ''
        ];
    }
}
bkhjykvo

bkhjykvo1#

Company模型中可能存在belongsTo关系。
您可以使用如下代码。

$company = Company::factory()
            ->for(User::factory()->state([
                'name' => 'User name',
            ]))
            ->create();

$user = User::factory()->create();
 
$company = Company::factory()
            ->for($user)
            ->create();

https://laravel.com/docs/9.x/eloquent-factories#belongs-to-relationships

相关问题