【问题标题】:How to create relationship through other model Laravel?如何通过其他模型 Laravel 创建关系?
【发布时间】:2020-03-30 13:26:14
【问题描述】:

我的项目中有一些模型,在这张图片中详细描述了不同的关系:

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

我想知道是否有可能建立关系,允许恢复教师的所有学生或学生的所有教师。

例子:

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

提前致谢

【问题讨论】:

    标签: php sql laravel laravel-5 eloquent


    【解决方案1】:

    您可以使用 Clase 作为数据透视表来定义多对多关系:
    在您的 Student 类中(假设 'clase' 是表名):

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

    【讨论】:

    • 好主意,它的作品,但有重复的老师条目,谢谢
    • 您可以在末尾添加->distinct() 以仅返回唯一行。
    【解决方案2】:

    因为这是一个特殊的关系,你需要定义所有的外键,他们完美地描述了in the documentation

    我认为这对你有用:

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

    【讨论】:

    • 是的,这是一个特殊的关系,我试过了,它不起作用,它在字段名称或空集合上返回错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多