thephpleague / factory-muffin

Enables the rapid creation of objects for testing
https://factory-muffin.thephpleague.com/
MIT License
531 stars 72 forks source link

[Help] Relationship Issues #410

Closed ddelnano closed 8 years ago

ddelnano commented 8 years ago

I am having trouble figuring out if this package fits my use case. Previously I used [Laracasts\Testdummy]() and I am trying to replace it with something framework agnostic. At first glance this package looked like the solution to my problems. However, after attempting to integrate it I have run into issues. The problems I am having have to do with complex relationships.

For example in my application lets say I have 3 models:

<?php

use League\Factory\Facade as Factory;

Factory::define(Business::class, [
// ..... Many more attributes
    "facebook_page_id" => 'factory|' . FacebookPage::class
]);

Factory::define(Restaurant::class, [
    "biz_id" => "factory|" . Business::class,
// .... Many more attributes
    "facebook_page_id" => "factory|" . FacebookPage::class
]);

Factory::define(FacebookPage::class, [
    'facebook_page_id' => $faker->unqiue()->randomNumberBetween(0, 20000)
]);

So in this situation the way I created a restaurant in Laracasts\Testdummy in order to avoid creating multiple FacebookPages I would create a FacebookPage and pass the facebook_page_id to both the business and restaurant class like so.

<?php

$facebookPage = Factory::create(FacebookPage::class);

$business = Factory::create(Business::class, ['facebook_page_id' => $facebookPage->facebook_page_id);

$restaurant = Factory::create(Restaurant::class, [
    'facebook_page_id' => $facebookPage->facebook_page_id,
    'business_id' => $business->biz_id
]);

I have had success with models that do not have relationships where I try to override it with the Factory::create method, however, for this example I get MySQL Error: Duplicate entry '5614' for key 'PRIMARY' for my FacebookPage model. So to me it seems like FactoryMuffin is still trying to save the relationship even though I am only passing an ID. Is this correct? I was wondering if what I am describing is possible?

ddelnano commented 8 years ago

Fixed this, it was an issue with trying to generate primary keys with faker and I used a closure like was suggested at this issue.