Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

php - How to update a related model in Laravel Eloquent

Here the scenario is, I have 3 models/tables: 1. Teacher 2. Course 3. Course Assign to Teacher

In the Teacher model/table there are two columns named: credit_taken and remaining_credit (default 0) and in the Course model/table there is a course_credit column.

So here is the problem: in the model/table Course Assign to Teacher when a Teacher takes a Course the value of this column should be calculated like this: remaining_credit = credit_taken - course_credit

I have implemented this, however instead of the value updating in database it's creating a new row in the Teachers table.

Here is my controller:

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');
}

How do I update above two columns in teacher table instead of inserting a new record.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try with this:

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');
}

and if you want to insert course should be create $course=new Course();


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...