2017-08-29 13 views
-1

私は二つの別々のテーブルstudentstutorsを持っています。ピボットテーブルstudents_tutorsには、2つの値students_studentidtutors_tutidが設定されています。物事の流れの中で、クライアントはチューターを学生に割り当てたり、その逆に、チューターを追加したり、後で編集したりすることができます。したがって、学生には多くの教師がおり、教師には多くの生徒がいるかもしれません。このような選択が行われると、ピボットテーブルの値が自動的に更新されるようになりました。複数の教師/生徒を一度に割り当てることができます。私はピボットテーブルの自動更新に問題があります。私はLaravelにとってかなり新しいです。誰もそれをどのように使うべきか、使用するコード、ピボット値を更新して表示する場所を誰にでも提案できますか?学生のためのピボットテーブルの値を自動的に更新する方法

マイadd.blade.php

<select name="tutid" id="tutors" multiple> 
    @foreach($tutors as $tutor) 
     <option value="{{$tutor->tutid}}">{{$tutor->name}}</option> 
    @endforeach 
</select> 

マイStudentモデル:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Student extends Model 
{ 
    protected $primaryKey = 'studentid'; 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function Tutors() 
    { 
     return $this->belongsToMany(Tutors::class); 
    } 

    public function Invoices() 
    { 
     return $this->belongsToMany(Invoices::class); 
    } 
} 

マイTutorモデル:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Tutor extends Model 
{ 
    protected $guarded = []; 

    protected $primaryKey = 'tutid'; 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function Students() 
    { 
     return $this->belongsToMany(Students::class); 
    } 
} 

私の学生コントローラーadd()方法:

public function add(Student $student, Tutor $tutor) 
{ 
    $students = Student::all(); 

    $tutors = Tutor::all(); 

    return view('students.add', compact('students', 'tutors')); 
} 
あなたが何ができるかをここで
+1

これまでに行ったことを示すことはできますか?私はモデルとマイグレーションを意味します。 – louisfischer

+0

はい、お願いします。若干の研究努力を示してください:) – quinz

+0

@louisfischerあなたが参照しているコメントのようであるため、https://stackoverflow.com/review/suggested-edits/17178443を承認したい場合は、質問にフラグを立てる必要があります。見つけることができません。 –

答えて

0

: ループ全ての生徒IDやチューターのIDを通って、私たちは家庭教師に複数の生徒を割り当てたい場合は、例につき を割り当てる:

$tutor = Tutor::find($id); 
foreach($students_id as $student_id){ 

    $tutor->students()->attach($student_id); 

} 

注意あなたがしなければならないことあなたのチューターモデル内の関係(学生)を持っている:

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

学生のための同じ操作を行う!

+0

@sletherenと他のみんなありがとうございます。私は悪夢を私がしたことを貼り付けていた。決して気にしないでください。私の価値観では、次のようになります: '$ tutor = Tutor :: find($ id); foreach($ studentidとしての$ studentid){ $ tutor-> students() - > attach($ studentid); 'これはどこで使うべきですか? TutorsControllerの私のストアメソッドで? –

+0

問題は、今のように見えます。 'public function store(Request $ request) { $ tutor =新しいチューター; $ tutor-> user_id = auth() - > id(); $ tutor-> studentid = request( 'studentid'); $ tutor-> name = request( 'name'); $ tutor-> contact = request( 'contact'); $ tutor-> subjects = request( '科目'); $ tutor = Tutor :: find($ id);} –

+0

また、私は複数の選択された生徒/教師を迎えたいと思っています。これらはそれぞれの追加ビューで関連するフォームから選択されています。その場合、これは機能しますか? –

関連する問題