如何通过其他模型Laravel建立关系?

时间:2019-12-05 15:13:29

标签: php sql laravel laravel-5 eloquent

我的项目中有一些模型,其中有不同的关系,如图所示:

Diagram

我创建了一些模型来代表每个表。

我想知道是否有可能建立一种关系,以恢复所有老师或学生的老师。

示例:

class Student extends Model
{
    public function clases(){
        return $this->hasMany(Clase::class, 'student_id');
    }

    /** This function doesn't works, not the great relation */
    public function teachers(){
        return $this->hasManyThrough(Clase::class, Teacher::class, 'student_id', 'teacher_id');
    }
}

我正在使用Laravel 5.8

预先感谢

2 个答案:

答案 0 :(得分:1)

您可以将Clase用作数据透视表来定义多对多关系:
在您的学生班级中(假设“ clase”为表名):

public function teachers(){
    return $this->belongsToMany(Teacher::class, 'clase', 'student_id', 'teacher_id');
}

答案 1 :(得分:0)

因为这是一个特殊的关系,所以您需要定义所有外键,它们in the documentation的描述很完美。

我认为这对您有用:

return $this->hasManyThrough(
    Teacher::class, 
    Clase::class, 
    'student_id', 
    'user_id',
    'user_id',
    'teacher_id'
);
相关问题