mpociot / laravel-test-factory-helper

Generate Laravel test factories from your existing models
935 stars 87 forks source link

Allow override relations columns #37

Closed markinigor closed 5 years ago

markinigor commented 5 years ago

It allows to override value without creating another model instance. It works like a closure

'user_id' => function () {
            return factory(App\User::class)->create()->id;
        }
jasonmccreary commented 5 years ago

Not sure I understand this. Could you elaborate as the changes don't line up with the PR comments. What are you suggesting the closure does that the inline reference does not?

markinigor commented 5 years ago

Without this request relations factories allway wil create model, even if we override the attribute

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'company_id' => factory(App\Company::class)->create()->id,  //Always creates model, even we override attribute
    ];
});
factory(App\User::class)->create([
    'company_id' => factory(App\Company::class)->create()->id
])

echo App\Company::count();  // Will return 2,  but we expect  1

With this PR:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'company_id' => factory(App\Company::class),  //Creates model and return its id only when the attribute does not exists in factory params.
    ];
});
factory(App\User::class)->create([
    'company_id' => factory(App\Company::class)->create()->id
])

echo App\Company::count();  // Will return 1
jasonmccreary commented 5 years ago

Interesting. Thanks for the explanation, I see now what you are trying to prevent. I am going to review the docs and core as this is interesting behavior.

jasonmccreary commented 5 years ago

Both of the examples you provided return 2 for me. This is actually more of a PHP lazy-execution thing, than a Laravel thing.

I am going to close this and open a new PR to wrap the relationships in a closure as they are outlined in the docs that way.

markinigor commented 5 years ago

Hm, It's weird. Any way Closure will be great too. P.s. This tip for a factory I see in Laracasts https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 at 14:01

jasonmccreary commented 5 years ago

Nice. Going to close this and submit a fresh patch. Thanks for all the feedback.