简体   繁体   English

与php中的FactoryMuffin一对多关系?

[英]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. 我试图使用FactoryMuffin(类似于FactoryGirl的php工厂库)为集成测试生成测试数据。

In my application, a Person can have many Emails and many Tokens . 在我的应用程序中,一个Person可以有许多Emails和许多Tokens I'd like to generate a Person with five Emails and one Token in my factory, and write some tests around it. 我想产生一个Person有五个Emails和一个Token在我的工厂,并写它周围的一些测试。

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. 我的问题是,当我创建一个Person ,它不会创建任何关联的EmailToken When I create a Token , it automatically creates a Person , but no associated Email s. 创建Token ,它会自动创建一个Person ,但不会创建关联的Email

How can I handle this? 我该如何处理?

Based on the way Factory Muffin works, you don't need to create persons. 根据Factory Muffin的工作方式,您无需创建人员。 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并按如下方式访问此Person

$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 您甚至可以走得更远,像这样为同一个人创建100封电子邮件和50个令牌

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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