我有一个用户,学生,课程和主题表
Student表的user_id与我建立了一对一的关系,因为学生是用户。
因此,在我的学生报告中,我有一个创建功能,可以获得该学生目前注册的所有课程科目,我这样做了:
public function create()
{
$user_id = Auth::user()->id;
$student_id = Student::where('user_id', $user_id)->first();
$course = $student_id->course->id;
$subjects = Subject::where('course_id', $course)->get();
return view('student.create', compact('subjects'));
}
视图如下所示:
{!! Form::open(['method' => 'POST', 'action'=>'StudentRegistration@store', 'files'=>true]) !!}
@foreach($subjects as $subject)
<div class="label-box">
{!! Form::label('subject_id', $subject->name) !!}
{!! Form::checkbox('subject_id[]', $subject->id, null, ['class'=>'form-control']) !!}
</div>
@endforeach
<div class="form-group">
{!! Form::submit('Create User', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
然后在store方法中,我设法更新数据透视表(student_subject)
public function store(Request $request)
{
$data = $request->except('_token');
$subject_count = count($data['subject_id']);
for($i=0; $i < $subject_count; $i++){
$student = Student::where('user_id', Auth::user()->id)->first();
$student->subjects()->attach($data['subject_id'][$i]);
}
但是,我注意到即使学生注册了某个特定科目,同一科目仍会在注册索引视图中显示,这将导致他进行双重注册。
那么,我怎样才能只查看学生所属的课程主题,而这些主题还没有在数据透视表中呢?
答案 0 :(得分:0)
因为您正在使用Laravel Collections,我建议使用Laravel提供的以下方法。
https://laravel.com/docs/5.6/collections#method-diffassoc
希望这可以帮助您解决问题。
答案 1 :(得分:0)
Route::get('/studentsubjects', function(){
$student_id = Student::where('user_id', Auth::id())->first();
$course = $student_id->course->id;
$subjects = json_decode($student_id->subjects);
$subjects2 = json_decode(Subject::where('course_id', $course)->get());
$subjectsUserNotRegisterd= array_udiff($subjects , $subjects2, function ($obj1, $obj2) {
return $obj1->id-$obj2->id;
});
echo "<pre>", print_r($subjectsUserNotRegisterd, 1);
});
结果:
Array
(
[3] => stdClass Object
(
[id] => 5
[course_id] => 1
[lecturer_id] => 1
[code] => Nss101
[name] => Network Systems
[created_at] => 2018-05-31 17:43:08
[updated_at] => 2018-05-31 17:43:08
)
)
答案 2 :(得分:0)
我使用laravel docs将Route改为以下代码,它的工作原理非常完美:
Route::get('/studentsubjects', function(){
$student_id = Student::where('user_id', Auth::id())->first();
$course = $student_id->course->id;
$all_subjects = $student_id->subjects;
$selected_subjects = Subject::where('course_id', $course)->get();
$nonregistered_subjects = $selected_subjects->diff($all_subjects);
foreach ($nonregistered_subjects as $nonregistered) {
echo $nonregistered->name;
}
});