Vinelab / NeoEloquent

The Neo4j OGM for Laravel
MIT License
633 stars 197 forks source link

Factories implementation #340

Closed iyhunko closed 3 years ago

iyhunko commented 3 years ago

Now it will be possible to generate Eloquent models(factory(xxx)->make()/ factory(xxx)->create()) via default Laravel's factory() helper function.

Issue details: Previously when we tried to factory(FooModel:class)->create(), we had next issues:

  1. Wrong check for Model(abstract class Illuminate\Database\Eloquent\Model) instance that is used in default Illuminate\Database\Eloquent\FactoryBuilder.php thus when we try to create 1 model, it thinks that we try to create a collection of models and we get the each() method does not exists... error.

    /**
     * Create a collection of models and persist them to the database.
     *
     * @param  array  $attributes
     * @return mixed
     */
    public function create(array $attributes = [])
    {
        $results = $this->make($attributes);
    
        if ($results instanceof Model) {
            $this->store(collect([$results]));
        } else {
            $this->store($results);
        }
    
        return $results;
    }
  2. Issue in default Illuminate\Database\Eloquent\FactoryBuilder.php (store() method) about non-existing getName() method... Was:

    protected function store($results)
    {
        $results->each(function ($model) {
            if (! isset($this->connection)) {
    
                $model->setConnection($model->newQueryWithoutScopes()->getConnection()->getName());
            }
    
            $model->save();
        });
    }

    will be:

/**
 * Set the connection name on the results and store them.
 *
 * @param  \Illuminate\Support\Collection  $results
 * @return void
 */
protected function store($results)
{
    $results->each(function ($model) {
        if (! isset($this->connection)) {
            $model->setConnection($model->getConnectionName());
        }
        $model->save();
    });
}