S
S
Sergey Chazov2020-08-04 09:30:48
Laravel
Sergey Chazov, 2020-08-04 09:30:48

How to create seed factory with related models in laravel?

I can’t understand why I can’t get such a factory:

factory(Company::class, 10)->create()->each(
            function (Company $company) {
                $company->chart()->save(factory(Chart::class)->make());
            }
        );

Company is related to Chart like this:
public function chart()
    {
        return $this->hasOne(\App\Models\Chart::class);
    }

And Chart is connected to Company like this:
public function company()
    {
        return $this->belongsTo(\App\Models\Company::class);
    }

I am getting this error:
Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db`.`companies`, CONSTRAINT `companies_chart_id_foreign` FOREIGN KEY (`chart_id`) REFERENCES `charts` (`id`)) (SQL: insert into `companies` (`name`, `admin_id`, `created_at`, `updated_at`, `chart_id`, `logo`) values (eveniet, 5, 1974-12-23 08:42:11, 1985-12-16 16:29:54, 9, perferendis))

Strange.. I thought he would first create a chart for me, then transfer the ID to the company and then save the company... But that doesn't work. How to write it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sundukov, 2020-08-04
@alekciy

Save the Chart first, and only then add it to Company. Those. in save should go Chart the saved model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question