简体   繁体   中英

One-To-Many relationships with FactoryMuffin in php?

I am trying to use FactoryMuffin, a php factories library similar to FactoryGirl, to generate test data for my integration tests.

In my application, a Person can have many Emails and many Tokens . I'd like to generate a Person with five Emails and one Token in my factory, and write some tests around it.

Currently, I am defining my factories like this:

FactoryMuffin::define('Person')->setDefinitions([
    'id'         => Faker::numberBetween(123456789, 987654321),
    'name'      => Faker::name()
]);

FactoryMuffin::define('Email')->setDefinitions([
    'id'         => Faker::numberBetween(123456789, 987654321),
    'address'      => Faker::email(),
    'person_id' => 'factory|Person',

]);

FactoryMuffin::define('Token')->setDefinitions([
    'token'         => Faker::numberBetween(1234567891234, 9876543211234),
    'person_id' => 'factory|Person',

]);

My problem is, when I create a Person , it does not create any associated Email s or Token s. When I create a Token , it automatically creates a Person , but no associated Email s.

How can I handle this?

Based on the way Factory Muffin works, you don't need to create persons. You can simply create emails and access the person that email created (the other way around). In the below example, we create a Message and then access the User that Message created for us.

Consider this example from their docs .

$message = FactoryMuffin::create('Message');
$this->assertInstanceOf('Message', $message);
$this->assertInstanceOf('User', $message->user);

In your case, you could create an Email and access the Person like below

$email = FactoryMuffin::create('Email');
$emailPerson = $email->person;

You can even go further and create 100 emails and 50 tokens for the same person like so

$person = FactoryMuffin::create('Person');
$emails = FactoryMuffin::seed(100, 'Email', ['person_id' => $person->id]);
$tokens = FactoryMuffin::seed(50, 'Token', ['person_id' => $person->id]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM