0

由于这个“新”更新出现在 laravel(laravel 8)中,我正在与工厂作斗争。我需要有关如何将用户模型中的唯一 ID 提供给配置文件工厂中的 user_id 列的帮助。在我的用户模型中,我与个人资料有关系:

public function profile()
{
    return $this->hasOne(Profile::class);
}

在轮廓模型中:

public function user()
{
    return $this->belongsTo(User::class);
}

现在我必须向配置文件工厂提供数据:

 return [
        'user_id' => ,
        'image' => 'image',
        'bio' => $this->faker->sentence,
...
4

1 回答 1

1

如果你只Profile在已有对应的 时创建User,你可以离开user_id工厂Profile,然后使用魔术方法同时创建两者。

User::factory()->hasProfiles(1)->create();

这将自动创建一个配置文件以匹配用户。


或者,如果您确实需要在创建用户之前创建配置文件,您可以在您的工厂user_id中定义这样的,并且 a将由.UserProfile

return [
    'user_id' => User::factory(),
    'image' => 'image',
    'bio' => $this->faker->sentence,
];
于 2020-11-19T17:32:38.477 回答