Answer the question
In order to leave comments, you need to log in
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());
}
);
public function chart()
{
return $this->hasOne(\App\Models\Chart::class);
}
public function company()
{
return $this->belongsTo(\App\Models\Company::class);
}
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))
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question