I have a users table and a one-to-zero/one relation with a businesses table (users.user_id => businesses.user_id). On my users table I have a discriminator which tells me if the user is of type business and therefore I need to have details on the businesses table as well.

I want to create my Users with my factory which currently is working and then only create business details where the discriminator points to a business account.

I have three options in my mind:

  1. Create from users factory and then using '->each()' do some checks on the discriminator and create a new business user using a the factory. However I cannot pass to the business factory the user_id that the user was assigned.
  2. 首先创建用户.然后在我的业务seeder 中,检索与"业务"鉴别器匹配的所有用户.然后为所有这些用户运行一个创建业务细节的工厂.但同样,我必须以某种方式将已经创建的用户的user_id与business factory user_id联系起来.
  3. In my business factory, create a new User and retrieve the id, thus making the link between users.user_id and business.user_id. However I am using a random generator for user.user_type so even if I have the businesses table filled it might be for users that have the discriminator as 'personal'.

还有别的办法吗?我能把我的 seeder 机传给工厂吗?

推荐答案

传递给create函数的属性将作为第二个参数传递到模型定义回调中.


在您的情况下,您甚至不需要访问这些属性,因为它们将自动合并到:

$business = factory(App\Business::class)->create();

factory(App\User::class, 5)->create([
    'business_id' => $business->id,
]);

Adapt this to your needs.

Laravel相关问答推荐

Laravel:如何从不断更新的Controller中分页数据

如何避免谷歌翻译翻译:参数

未找到 apiResource 404 中的变量

在 Laravel 中清除 Routes&config:cache 后未定义的常量

Laravel 连接表

Laravel 集合排序不生效

Laravel 6 Passport 在错误的凭证上返回 400 Bad request

Laravel + SQLite = SQLSTATE[HY000]一般错误:8次try 写入只读数据库

在Laravel 5中通过ID和所有递归获取记录

在 laravel 如何将额外的数据传递给 mutators 和 accessors

查询构建器中的 Laravel 5 多重 Select ()

php Laravel-遇到格式不正确的数值(在字符串上)

Composer 致命错误:声明 Fxp... 必须与第 334 行的 ...AbstractAssetsRepository.php 兼容

从 Artisan 电话中获得响应

如何重定向到laravel上的公共文件夹

如何在laravel 5.1中使用url(路由)传递多个参数

Laravel homestead IP地址不起作用

Laravel binding绑定的用途和目的是什么?

如何在laravel中 for each 用户生成唯一的随机值并将其添加到数据库中

Laravel 4 - 文件上传