tag
3 years ago

Model Factories creating Many To Many relationships with reusability

Posted 3 years ago by tag

Here's a simple example. I have a Product model, and products have many Download objects. For testing purposes, when I create a new product from my model factory, I always want it to create a few Download objects and attach them. I like the portability of simply specifying:

factory(\App\Product::class)->create()

In my tests, and I don't want to have to do this every time I want to create a product to test with:

factory(\App\Product::class, 10)->create()->each(function($product){
    $downloads = factory(\App\Download::class, 10)->create();   
    $product->downloads()->attach($downloads->pluck('id'));
});

I don't want to seed these with regular seeders, as I want to be able to create them on-the-fly with a simple API like the factory method.

Save for creating a new helper function which acts as a pass-through intermediary to the factory helper, I don't see a way to utilize the model factories for these many to many relationships.

Has anyone overcome this problem simply?

EDIT: I basically want to be able to do this:

$factory->defineAs(App\Product::class, 'download', function (Faker\Generator $faker) use ($factory) {
    $product_type = App\ProductType::where('machine_name', 'download')->first();    
    $product = $factory->raw(App\Product::class);
    $data = [
        'product_type_id' => $product_type->id,
    ];
    return array_merge($product, $data);
})->each(function($product){
    $downloads = factory(\App\Download::class, 10)->create();   
    $product->downloads()->attach($downloads->pluck('id'));
});

Please sign in or create an account to participate in this conversation.