我在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' => ''
];
}
}
1条答案
按热度按时间bkhjykvo1#
在
Company
模型中可能存在belongsTo
关系。您可以使用如下代码。
或
https://laravel.com/docs/9.x/eloquent-factories#belongs-to-relationships