2017-08-29 22 views
-1

我有兩個單獨的表studentstutors。我也有數據透視表students_tutors設置了兩個值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 as $ studentid){ $ tutor-> students() - > attach($ studentid);'但是,我應該在哪裏使用它?在我的TutorsController的商店方法? –

+0

問題是,它現在看起來像這樣。 '公共功能店(Request $ request) { $ tutor =新導師; $ tutor-> user_id = auth() - > id(); $ tutor-> studentid = request('studentid'); $ tutor-> name = request('name'); $ tutor-> contact = request('contact'); $ tutor-> subjects = request('subjects'); $ tutor = Tutor :: find($ id);}' –

+0

此外,我希望能夠挑選多個選定的學生/導師,這些都是從相應的表單中挑選出來的。這在這種情況下會起作用嗎? –