Search code examples
codeception

ManyToMany relationships with FactoryMuffin in php?


I'm using Codeception and I have an entity Courier related by a ManyToMany relations to users.

I'm using the have method from DataFactory like this

$courier = $I->have(Courier::class);
$courier->addOwner($user);

But I would like to do it like this

$courier = $I->have(Courier::class, ['owners' => [$user]]);

Is this possible?


Solution

  • I found this solution

    $courier = $I->have(Courier::class, ["addThisOwners" => [$user1]]);
    
    $factory->_define(Courier::class, [
        "subject" => Faker::word(1, 5),
    ])->setCallback(function ($obj) {
        foreach ($obj->addThisOwners as $owner) {
            $obj->addOwner($owner);
        }
    });