我是 Laravel 新手, 我想从 xlsx 文件将学生详细信息插入 mysql 数据库。 我使用 Laravel excel v3 导入 excel 文件。它运行良好。但是,除了在 1 个表中插入学生详细信息之外,还应在所有关联表中创建相同的学生 ID 记录。
示例--> 如果在“student_details”表中插入 1 个学生,则必须在“oral”和“endsem”表中创建 1 条记录,外键为“student_id”。
我已经举办了活动,在口头表和最终表中记录这些记录。 现在的问题是如何应用该事件以及如何在创建学生以触发事件后获取学生 ID。 (学生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',
]
];
}
}
我的主要目标是当学生插入“student_details”表时,将学生记录插入具有外键“student_id”的所有关联表中。 如果还有其他方法,请帮忙。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
而不是使用
Maatwebsite\Excel\Concerns\ToModel您可以使用Maatwebsite\Excel\Concerns\OnEachRow。您可以更好地控制每一行发生的情况。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([...]); } }至于让这一切在事务中发生: