Laravel:如何插入多条记录

时间:2015-03-09 07:39:42

标签: laravel laravel-4 eloquent laravel-5

我想使用Laravel在我的数据库中插入多个记录,但是当我插入它时,它只给我一个数据库中的记录

这是我的控制器

    public function postCreateAttendance()
{
    $validate = Validator::make(Input::all(), array(
        'status' => 'required'
    ));


    if ($validate->fails())
    {
        return Redirect::route('viewStudent')->withErrors($validate)->withInput();
    }
    else
    {





        foreach(User::all() as $user):
        foreach(User::whereRaw('isTeacher = "0" and isAdmin = "0"')->get() as $student)
        foreach(User::whereRaw('isTeacher = "1" and isAdmin = "0"')->get() as $teacher)
        //$users[$user->id]=$user->firstname;




        $attendance = new Attendance();
        $attendance->status = Input::get('status');
        $attendance->comment = Input::get('comment');
        $attendance->student_id = $student->id=$student->id;
        $attendance->student_firstname = $student->id=$student->firstname;
        $attendance->student_lastname = $student->id=$student->lastname;
        $attendance->teacher_id = $teacher->id=$teacher->id;
        $attendance->teacher_firstname = $teacher->id=$teacher->firstname;
        $attendance->teacher_lastname = $teacher->id=$teacher->lastname;






        if($attendance->save())
        {
            return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
        }
    else
    {
        return Redirect::route('viewStudent')->with('fail', 'An error occured while creating the attendance.');
    }


        endforeach;


    }
}

如何保存多条记录?请帮忙谢谢^ _ ^

1 个答案:

答案 0 :(得分:1)

问题是你在foreach循环期间return - 所以只处理了一条记录。您需要处理所有记录,然后返回路线。

以下是您的代码的重构

public function postCreateAttendance()
{
    $validate = Validator::make(Input::all(), array(
        'status' => 'required'
    ));


    if ($validate->fails()) {
        return Redirect::route('viewStudent')->withErrors($validate)->withInput();
    }

        foreach(User::where('isTeacher', '0')->where('isAdmin', '0')->get() as $student) {
              foreach(User::where('isTeacher', '1')->where('isAdmin', '0')->get() as $teacher) {

                    $attendance = new Attendance();
                    $attendance->status = Input::get('status');
                    $attendance->comment = Input::get('comment');
                    $attendance->student_id = $student->id;
                    $attendance->student_firstname = $student->firstname;
                    $attendance->student_lastname = $student->lastname;
                    $attendance->teacher_id = $teacher->id;
                    $attendance->teacher_firstname = $teacher->firstname;
                    $attendance->teacher_lastname = $teacher->lastname;
                    $attendance->save();
               }
          }

      return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
}

编辑:我已删除了第一个foreach(User::all() as $user): - 因为目前,在您的代码中,它什么也没做??