簡體   English   中英

如何將記錄添加到 Laravel 中的數據透視表

[英]How to add records to a pivot table in Laravel

我有一個用戶、學生和科目模型,我想將一名學生注冊到許多科目中。 所以我創建了一個 StudentRegistration 控制器,並在我的創建視圖中顯示屬於當前登錄用戶的課程的所有主題。

StudentRegistration.php 創建函數

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('name', $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() !!}

我在我的 Student.php 中有這個用於多對多關系:

public function subjects()
{
    return $this->belongsToMany('App\Subject');
}

我創建了一個名為 Student_Subject 的數據透視表。 因此,在商店期間,如何將所有選定的科目保存到數據透視表( 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);
       $student->subjects()->attach($data['subject_id'][$i]);
    }
}

但我收到以下錯誤:

"Method Illuminate\Database\Query\Builder::subjects does not exist."

以及如何查看學生未注冊的所有課程科目?

我有這個:

Route::get('/studentsubjects', function(){
    $student_id = Student::where('user_id', Auth::id())->first();
    $course = $student_id->course->id;
    $subjects = $student_id->subjects;

    echo 'Registered at' .'<br>';
    foreach ($subjects as $registered) {
        echo $registered->name .'<br>';
    }

    $unregistered = Subject::where('course_id', $course)->except($subjects);
});

並看到這個錯誤:

"Method Illuminate\Database\Query\Builder::except does not exist."
$student = Student::where('user_id', Auth::user()->id);

不足以獲取 Student 模型,您只能在這里獲取查詢對象。

為了實際獲得學生,請使用以下內容:

$student = Student::where('user_id', Auth::user()->id)->first();

如果user_id是模型Student的主鍵,那就更好了:

$student = Student::find(Auth::user()->id);

作為旁注,您可以使用Auth::id()而不是Auth::user()->idAuth接口直接訪問用戶 ID,結果:

$student = Student::find(Auth::id());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM