首页 > 解决方案 > laravel 质量分配问题。适用于“ModelName::insert($array)”但不适用于“ModelName::create($array)”

问题描述

在下面的示例代码中,我想每次使用作业获取所有已保存的学生 ID:


for ($i=0; $i < $count; $i++)
        { 
         $student_array[] = array(
                      'user_id'                  =>   $login_user_id,
                      'first_name'               =>   $student_first_name[$i],
                      'middle_name'              =>   $student_middle_name[$i],
                      'last_name'                =>   $student_last_name[$i],
                      'siblings_first_name'      =>   $siblings_first_name ?? NULL,
                      'siblings_middle_name'     =>   $siblings_middle_name ?? NULL,
                      'siblings_last_name'       =>   $siblings_last_name ?? NULL,
                      'going_to_grade'           =>   $going_to_grade[$i],
                      'photo'                    =>   $img_name,
                      'dob'                      =>   $dob[$i],
                      'place_of_birth'           =>   $place_of_birth[$i],
                      'student_nationality'      =>   $nationality[$i],
                      'religion'                 =>   $religion[$i],
                      'blood_group'              =>   $blood_group[$i],
                      'passport_no'              =>   $passport_no[$i],
                      'passport_place_of_issue'  =>   $passport_place_of_issue[$i],
                      'passport_date_of_issue'   =>   $passport_issue_date[$i],
                      'passport_date_of_expiry'  =>   $passport_expiry_date[$i],
                      'civil_id_no'              =>   $civil_id_no[$i],
                      'civil_id_date_of_expiry'  =>   $civil_id_expiry_date[$i],
                      'specify_child_illlness'   =>   $illlness[$i] ?? NULL,
                      'status'                   =>   'IA',
                      'created_at'               =>   date('Y-m-d h:i:s', time())
                   );


               }
               /* work fine with insert 
                $student_save = StudentDetail::insert($student_array);
               */ 
              //error with create
               $student_save = StudentDetail::create($student_array);

型号代码为:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class StudentDetail extends Model
{
     protected $table = 'student_details';

     protected $guarded = [];
}

错误消息:jquery-2.2.4.min.js:4 POST http://127.0.0.1:8000/new-registration/store 500(内部服务器错误)

在此处输入图像描述

标签: phplaravelmass-assignment

解决方案


您将$student_array其视为正在添加的行的运行集合,您需要将单个行传递给StudentDetail::create().

我认为,而不是这个:

$student_save = StudentDetail::create($student_array);

你打算这样做:

$student_save = StudentDetail::create($student_array[$i]);

$i用于引用您添加到的最后一行$student_array和您要传递到的行StudentDetail::create()


推荐阅读