我是 Laravel 新手, 我想從 xlsx 文件將學(xué)生詳細信息插入 mysql 數(shù)據(jù)庫。 我使用 Laravel excel v3 導(dǎo)入 excel 文件。它運行良好。但是,除了在 1 個表中插入學(xué)生詳細信息之外,還應(yīng)在所有關(guān)聯(lián)表中創(chuàng)建相同的學(xué)生 ID 記錄。
示例--> 如果在“student_details”表中插入 1 個學(xué)生,則必須在“oral”和“endsem”表中創(chuàng)建 1 條記錄,外鍵為“student_id”。
我已經(jīng)舉辦了活動,在口頭表和最終表中記錄這些記錄。 現(xiàn)在的問題是如何應(yīng)用該事件以及如何在創(chuàng)建學(xué)生以觸發(fā)事件后獲取學(xué)生 ID。 (學(xué)生ID將是auto_increment值)
StudentImport -->
<?php namespace App\Imports; use App\Events\StudentCreated; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Validators\Failure; use Maatwebsite\Excel\Concerns\Importable; use Maatwebsite\Excel\Concerns\SkipsOnFailure; use Maatwebsite\Excel\Concerns\WithValidation; use Maatwebsite\Excel\Concerns\SkipsFailures; use Maatwebsite\Excel\Concerns\WithHeadingRow; use App\Models\StudentDetails; class StudentsImport implements ToModel, SkipsOnFailure, WithValidation, WithHeadingRow { use Importable, SkipsFailures; /** * @param Collection $collection */ public function model(array $row) { return new StudentDetails([ 'roll_no' => $row['roll_no'], 'student_id' => $row['student_id'], 'div' => $row['div'], 'name' => $row['name'], 'gender' => $row['gender'], 'user_key' => session()->get('user_id'), 'group_key' => $group_key ]); } public function onFailure(Failure ...$failures) { // Handle the failures how you'd like. } public function rules(): array { return [ 'student_id' =>[ 'required', 'string', 'unique:student_details' ], 'roll_no' =>[ 'required', 'integer' ], 'name' => [ 'required', 'string', ] ]; } }
我的主要目標是當(dāng)學(xué)生插入“student_details”表時,將學(xué)生記錄插入具有外鍵“student_id”的所有關(guān)聯(lián)表中。 如果還有其他方法,請幫忙。
而不是使用
Maatwebsite\Excel\Concerns\ToModel
您可以使用 Maatwebsite\Excel\Concerns\OnEachRow
。您可以更好地控制每一行發(fā)生的情況。
use App\StudentDetails; use Maatwebsite\Excel\Row; use Maatwebsite\Excel\Concerns\OnEachRow; class StudentsImport implements OnEachRow, ... { public function onRow(Row $row) { $rowIndex = $row->getIndex(); $row = $row->toArray(); // create model $studentDetails = StudentDetails::create([ 'roll_no' => $row['roll_no'], 'student_id' => $row['student_id'], 'div' => $row['div'], 'name' => $row['name'], 'gender' => $row['gender'], 'user_key' => session()->get('user_id'), 'group_key' => $group_key /* this variable doesn't seem to be defined anywhere */ ]); // create related models $studentDetails->oral()->create([...]); $studentDetails->endsem()->create([...]); } }
至于讓這一切在事務(wù)中發(fā)生:
DB::transaction(fn () => (new StudentsImport)->import(...));