如何将参数传递给Laravel工厂? [英] How to pass arguments to Laravel factories?

查看:123
本文介绍了如何将参数传递给Laravel工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个users表以及与businesses表的一对零/一个关系(users.user_id => business.user_id).在我的users表上,有一个区分符,告诉我该用户是否是商务用户,因此我还需要在businesses表上提供详细信息.

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. 从用户工厂创建,然后使用'-> each()'对鉴别符进行一些检查,并使用工厂创建新的业务用户.但是,我无法将分配给用户的user_id传递给商业工厂.
  2. 首先创建用户.然后在我的业务播种机中,检索与业务"鉴别符匹配的所有用户.然后,为所有这些用户运行一个创建业务详细信息的工厂.但是同样,我必须以某种方式将已经创建的用户的user_id与业务工厂user_id链接.
  3. 在我的业务工厂中,创建一个新的User并检索ID,从而在users.user_idbusiness.user_id之间建立链接.但是,我正在为user.user_type使用随机生成器,因此,即使我填充了businesses表,它也可能适用于将区分符设为个人"的用户.
  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. First create the users. Then in my Business seeder, retrieve all Users that match a 'business' discriminator. Then for all of these users run a factory that creates the business details. But again, I would have to link somehow the user_id of the already create user with the 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'.

还有另一种方法吗?我可以将播种机的参数传递给工厂吗?

Is there another way? Can I pass arguments from my Seeder to the factory?

推荐答案

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

The attributes you pass to the create function will be passed into your model definition callback as the second argument.

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

In your case you don't even need to access those attributes, since they'll automatically be merged in:

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

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

根据您的需求进行调整.

Adapt this to your needs.

这篇关于如何将参数传递给Laravel工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆