V
V
VicTHOR2020-11-09 18:31:35
Laravel
VicTHOR, 2020-11-09 18:31:35

How to populate the fields of a pivot table when creating a record in a dependent table?

class Company
{
    public function documents()
    {
        return $this->belongsToMany(Document::class);
    }
}

// перебираю значения, нужно создать документ(если такого нет) и заполнить поля для связующей таблицы документов и компаний 
foreach($result['data']['documents'] as $document) {
                $company->documents()->firstOrCreate(
                    ['type' => $document['type']]
                );

                // нужно что-то такое
                $comapny->documents()->pivot([
                    'type' => $document['type'],
                    'series' => $document['series'],
                    'number' => $document['number'],
                ]);
            }


migration
Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->string('type');
        });

Schema::create('document_company', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Document::class);
            $table->foreignIdFor(Company::class);
            $table->string('category');
            $table->string('series');
            $table->string('number');
        });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
feycot, 2020-11-09
@VicTHOR

You can create a binding model, such as CompanyDocument, where you can add the necessary information.
It can be inherited from both Pivot and Model, working with it as with a normal model.
Contact info here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question