How to pass arguments to Laravel factories?

浪子不回头ぞ 提交于 2019-12-03 15:29:37

问题


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. 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?


回答1:


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.




回答2:


My code for adding polymorphic 'Admin' users was:

// run model factory
factory(App\Admin::class, 3)->create()->each(function ($admin) {

    $admin->user()->save(

        // solved: https://laravel.com/docs/master/database-testing#using-factories (Overriding attributes)
        factory(App\User::class)->make([
              'userable_id' => $admin->id,
              'userable_type' => App\Admin::class
        ])
    );
});

Hope this helps.



来源:https://stackoverflow.com/questions/32378215/how-to-pass-arguments-to-laravel-factories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!