2016-08-22 87 views
1

我在Laravel關係中有點困難。我完成了CourseModel,CourseTimeModel和CourseInstructorModel之間的所有關係。但問題是,我想從講師表中獲取instructor_name。有可能我可以從教師表使用關係中獲取instructor_name?Laravel Relationship的

CourseModel.php

class CourseModel extends Model { 

    protected $table = 'course'; 

    protected $fillable = [ 
     'course_name', 
     'fee', 
     'duration', 
     'description', 
     'created_at', 
     'updated_at', 
    ]; 

    public function courseInstructor() { 
     return $this->hasMany('App\CourseInstructorModel'); 
    } 

    public function courseTime() { 
     return $this->hasMany('App\CourseTimeModel'); 
    } 

    public function getCourses() { 
     $courses = $this->with(['courseTime', 'courseInstructor'])->paginate(10); 
     return $courses; 
    } 
} 

CourseInstructorModel.php

class CourseInstructorModel extends Model 
{ 
    protected $table = 'course_instructor'; 

    protected $fillable = [ 
     'course_id', 
     'instructor_id', 
     'created_at', 
     'updated_at', 
    ]; 

    public function course() 
    { 
     return $this->belongsTo('App\CourseModel');  
    } 
} 

CourseTimeModel.php

class CourseTimeModel extends Model 
{ 
    protected $table = 'course_time'; 

    protected $fillable = [ 
     'course_time', 
     'course_id', 
     'created_at', 
     'updated_at', 
    ]; 

    public function course() 
    { 
     return $this->belongsTo('App\CourseModel');  
    } 
} 
+0

哪裏錯誤?你在哪裏嘗試使用你的關係? –

+0

我試圖通過使用關係的CourseModel @ getCourses()來獲得所有課程。 –

+0

$ course = CourseModel :: find(n); $ course_instructors = $ course-> courseInstructor; $ course_times = $ course-> courseTime() - > paginate(10); –

回答

1

我使用CourseModel和InstructorModel之間的多對多關係解決了我的問題。 這裏是我的代碼,我在CourseModel.php

public function instructor() { 
    return $this->belongsToMany('App\Instructor'); 
} 
0

寫您可以通過這種方式獲得instructor_name:

$courseModel = CourseModel::find(1); 
$instructor_name = $courseModel->courseInstructor->instructor_name;