topclaudy / compoships

Multi-columns relationships for Laravel's Eloquent ORM
MIT License
1.12k stars 132 forks source link

Factory relationships support. Error: [Illegal offset type] #154

Closed didac-adria closed 1 year ago

didac-adria commented 1 year ago

Hello!

I think there is no support currently for the factories relationships for this package. Let me explain the problem I found: If you try to use a Laravel Factory and define a relationship, for instance using the ->has() method, it breaks. For example:

Model::factory()
->has(SecondModel::factory())
->count(5)
->create();

This will break if this is using a Compoships relationship. Why? After some investigation, I've seen that it comes from the Illuminate\Database\Eloquent\Factories\Relationship.php class. It doesn't have a Compoships equivalent. Therefore, when trying to call the createFor() method breaks here:


namespace Illuminate\Database\Eloquent\Factories;

class Relationship
{

  public function createFor(Model $parent)
      {
          [...]
          elseif ($relationship instanceof HasOneOrMany) {
              $this->factory->state([
                  $relationship->getForeignKeyName() => $relationship->getParentKey(),
              ])->create([], $parent);
          }
          [...]
      }

}

This is trying to add to the factory a new state. However, $relationship->getForeignKeyName() returns an array (with the relationship foreign keys), which fails when trying to assign it to an array's key. This needs to be split into each relationship key.

didac-adria commented 1 year ago

PR attached

parallels999 commented 1 year ago

@topclaudy merged, must be closed