如何在Laravel Eloquent中更新相关模型

时间:2016-05-03 08:46:36

标签: php laravel laravel-5 eloquent

这里的情况是,我有3个模型/表:  1. Teacher  2. Course  3. Course Assign to Teacher

Teacher模型/表中有两列名为:credit_takenremaining_creditdefault 0),在Course模型/表中有一个course_credit列。

所以这就是问题所在:在模型/表Course Assign to Teacher中,当Teacher占用Course时,此列的值应按如下方式计算:     remaining_credit = credit_taken - course_credit

我已经实现了这一点,但是在数据库中更新值而不是在Teachers表中创建一个新行。

这是我的控制器:

public function postcourseAssignTeacher(Request $request)
{
    $assignTeacher = new AssignTeacher();
    $assignTeacher->teacher_id = $request->Input(['teacher_id']);

    $teacher->credit_taken = $request->Input(['credit_taken']);
    $teacher->remaining_credit = $request->Input('remaining_credit');

    $assignTeacher->course_id = $request->input('course_id');

    $course->name = $request->Input('name');
    $course->credit = $request->Input('credit');

    $teacher->remaining_credit = $teacher->credit_taken -$course->credit;

    $assignTeacher->save();
    //    $course->save();

    $teacher->update();

    return redirect('courseAssignTeacherPage');
}

如何更新教师表中的上述两列,而不是插入新记录。

1 个答案:

答案 0 :(得分:1)

试试这个:

public function postcourseAssignTeacher(Request $request)
{
    $assignTeacher = new AssignTeacher();
    $assignTeacher->teacher_id = $request->Input(['teacher_id']);


$teacher=Teacher::find(Input($request->['teacher_id']);


 $teacher->credit_taken = $request->Input(['credit_taken']);
    $teacher->remaining_credit = $request->Input('remaining_credit');

    $assignTeacher->course_id = $request->input('course_id');

    $course->name = $request->Input('name');
    $course->credit = $request->Input('credit');

    $teacher->remaining_credit = $teacher->credit_taken -$course->credit;

    $assignTeacher->save();
    //    $course->save();

    $teacher->update();

    return redirect('courseAssignTeacherPage');
}

如果你想插入课程,应该创建$ course = new Course();