V
V
VicTHOR2020-11-10 17:18:56
Laravel
VicTHOR, 2020-11-10 17:18:56

Why didn't the key of the related table populate?

migration

Schema::create('companies', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->foreignIdFor(CompanyForm::class);


the code
$company = new Company();
$company->form()->firstOrCreate(
               // данные. Создается успешно.
            )
// code

$company->save();


$company->form()
public function form()
    {
        return $this->belongsTo(CompanyForm::class);
    }


Mistake
ERROR: null value in column "company_form_id" violates not-null constraint


Shouldn't company_form_id be automatically substituted?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
feycot, 2020-11-10
@feycot

Try to print what comes out in the form without creating.
This can be done in Laravel replay

php artisan tinker
>>> $u  = User::first()
[!] Aliasing 'User' to 'App\User' for this Tinker session.
=> App\User {#4365
     id: "1",
     name: "Sandrine Cormier",
     email: "[email protected]",
     email_verified_at: "2020-10-07 16:19:15",
     created_at: "2020-10-07 16:19:15",
     updated_at: "2020-10-07 16:19:15",
     deleted_at: null,
   }
>>> $u->completedExercises()->make([])
=> App\CompletedExercise {#4350
     user_id: 1,
   }
>>>

P
pLavrenov, 2020-11-12
@pLavrenov

1. create, update call save themselves.
2. Even to think logically, then the relationship is called to an empty object of the newly created model, where does it get this ID from ?.
3. Forget about new to models. With this, all the magic disappears.
In general, to be honest, this code shows that you need to read the documentation. It's all there with examples.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question