Laravel Relationship's

时间:2016-08-22 06:46:20

标签: php laravel

我在Laravel Relationships中有点困难。我在CourseModel,CourseTimeModel和CourseInstructorModel之间建立了所有关系。但问题是我想从讲师表中获取instructor_name。我可以使用关系从讲师表中获取instructor_name吗?

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');    
    } 
}

2 个答案:

答案 0 :(得分:1)

我使用CourseModel和InstructorModel之间的多对多关系解决了我的问题。 这是我在 CourseModel.php

中编写的代码
public function instructor() {
    return $this->belongsToMany('App\Instructor');
}

答案 1 :(得分:0)

您可以通过以下方式获取instructor_name:

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