工厂中的Laravel访问关系模型



我在一个Laravel 9项目中工作,我使用模型工厂。我有User,它可以有一个Company

我需要将CompanyFactory的详细信息链接到User,例如名字和姓氏。user_id已经被Laravel映射。

这是我的尝试,或者我认为我可以在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 DatabaseFactories;
use AppModelsUser;
use AppModelsCountry;
use AppModelsCompany;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesHash;
use IlluminateSupportStr;
use CarbonCarbon;
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' => ''
];
}
}

您可能在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

这是我在应用程序中使用播种器的解决方案。

$companies = CompanySettings::factory()->count($this->companiesToCreate)->create();
$companies->each(function ($company) {
// Add Primary User
$users = User::factory([
'company_id' => $company->id,
'account_status' => 1,
'paid' => true,
'subscriber' => true,
'role' => 'Primary Account',
'account_type' => 1
])->has(
GlobalSettings::factory([
'company_id' => $company->id
])->count(1), 'globalSettings'
)->count(1)->create();

});

相关内容

  • 没有找到相关文章