V
V
VicTHOR2020-11-11 12:57:11
Laravel
VicTHOR, 2020-11-11 12:57:11

How to bind id with hasOne?



There are company
id | name | form_id
forms tables
id | name

If the Company model has

public function form()
    {
        return $this->hasOne(Form::class);
    }
then how to work with it?

I create a new company
$company = new Company();
$company->name = 'some name';

$form = Form::firstOrCreate(); // передаются данные из запроса

How to fill in the form_id field for the company table without crutches?
Now it turns out to bind like this $company->form_id = $form->id;

. Is it possible to somehow bind form_id using the method form()in which it returns HasOne?
Or is this method not used for writing?

UPD
It's not even possible to return the associated model Form( laravel is looking for forms.company_id , which is not there), it just turned out like this
public function form()
    {
        return CompanyForm::find($this->form_id)->first();
    }

Is it done in some other way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-11-11
@VicTHOR

The logic is not clear at all. What is form and why is it so associated with company.
But if you take it as written, then the relationship should be form hasOne Company and company belongsTo form. in the form model

public function company()
{
    return $this->hasOne(Company::class);
}

and create a record
$form->company()->create($request->validated());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question