2017-08-29 17 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

此外,我希望能够挑选多个选定的学生/导师,这些都是从相应的表单中挑选出来的。这在这种情况下会起作用吗? –