Factory Muffin relationships are "null" when using instance method

时间:2015-05-12 22:58:14

标签: php mongodb laravel-5 factory-bot

I'm working on a Laravel 5 app using the jenssegers\laravel-mongodb package and I'm trying to get up and running with Factory Muffin to help with rapidly testing and seeding etc.

I have defined relationships in my factory definitions (code below) - and they work when I run seeds to create new records in the database. By "work", I mean they attach related data correctly to the parent model and persist all those records to the database. But they do not work when I run the [] rootProject [] childProject1 [] childProject2 [] childProject3 method, which creates a new instance without persisting it. All the relations come back as null.

In a way this makes sense. When the models are stored in the database, they are related by the object $muffin->instance('My\Object') key. That key doesn't exist until the model is stored. So when I call the _id method, I actually can see via debugging that it does generate the models that would be related, but it does not yet have any key to establish the relation, so that data just kinda goes poof.

This is a bummer because I'd like to be able to generate a fully fleshed-out model with its relations and see for example whether it is saved or passes validation and whatnot when I submit its data to my routes and things. I.e., right now I would not be able to check that the contact's email was valid, etc.

Simplified code samples are below - am I going about this in an entirely wrong way? This is my first time working with Mongo and Factory Muffin. Should this even be able to work the way I want it to?

instance

1 个答案:

答案 0 :(得分:0)

好的,为了让工厂松饼适当地充实mongo嵌入式关系,你必须这样做:

// factories/all.php

$embedded_contact = function() {
    $definitions = [
        'first_name' => Faker::firstName(),
        'email' => Faker::email(),
        // ... etc
    ];

    return array_map(
        function($item) { return $item(); },
        $definitions
    );
}

$fm->define('My\Models\Event', [
    'title' => Faker::text(75),
    'contact' => $embedded_contact
]);

如果这看起来很麻烦和苛刻......我同意!我非常有兴趣听到更简单的方法。现在我按照上面的步骤进行测试和播种。