php - 在 Eloquent 关系 laravel 中转换查询

标签 php mysql database laravel eloquent

我有 5 个表 students,teachers,subjects,student_subject,subject_teacher student 与 subject 有多对多的关系,同样 teacher 与 subject 有多对多的关系。

学生表

id | name | email

教师表

id | name | email

科目表

id | name 

subject_teacher 表:

id | teacher_id | subject_id

student_subject 表:

id | student_id | subject_id

上面是我的数据库结构 在Student,Teacher,Subject 模型中我定义了多对多关系。 因此,如果我想获得老师的科目,我只需执行 Teacher::find(1)->subjects()->get()。在我目前的数据库结构中,我没有学生和老师之间的直接关系,但我想让老师的所有学生都可以通过类似

的查询来做到这一点
 Student::join('student_subject', 'students.id', '=', 'student_subject.student_id')
 ->join('subject_teacher', 'student_subject.subject_id', '=', 'subject_teacher.subject_id')
 ->where('subject_teacher.teacher_id', '=',1)
  ->groupBy('students.name');

我的问题我不想查询我想 Eloquent 地做这件事我会做什么我会改变我的关系请帮助我

注意:我不想改变我的数据库结构。我知道如果可以通过查询实现,那么就可以通过 Eloquent 方式实现。

最佳答案

您无需更改表的结构即可使用 Eloquent。您所需要的只是创建 Eloquent 模型和定义关系。因此,让我们首先为 studentsteacherssubjects 创建模型。

学生模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model {

    public function subjects()
    {
        return $this->belongsToMany(Subject::class);
    }

}

教师模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Teacher extends Model {

    public function subjects()
    {
        return $this->belongsToMany(Subject::class);
    }

}

主题模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subject extends Model {

    public function students()
    {
        return $this->belongsToMany(Student::class);
    }

    public function teachers()
    {
        return $this->belongsToMany(Teacher::class);
    }

}

现在你可以使用这样的东西:

// Get all students with related subjects
$studentsWithSubjects = \App\Student::with('subjects')->get();

// Get student with id 1 with related subjects
$student1WithSubjects = \App\Student::with('subjects')->find(1);

使用与 Teacher 模型相同的规则。希望它能帮助您入门。

更新:

好吧,如果您想使用多对多 关系在TeacherStudent 模型之间建立关系,那么您需要使用 id、'student_id' 和 teacher_id 创建另一个数据透视表,然后在 TeacherStudent 中定义关系方法模型,因此您可以从两侧使用关系方法,例如:

// In Student Model
public function teachers()
{
    return $this->belongsToMany(Teacher::class);
}

// In Teacher Model
public function students()
{
    return $this->belongsToMany(Student::class);
}

所以现在你将能够使用这样的东西:

$teacher1WithStudents = \App\Teacher::with('students')->find(1);
$student1WithTeachers = \App\Student::with('teachers')->find(1);

关于php - 在 Eloquent 关系 laravel 中转换查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304124/

相关文章:

mysql - 其中查询计数结果 > 0

php - 不在 CODEIGNITER Mysql 中插入数据库

database - 如何标记表格的选定列以供显示

php - mysql_fetch_array() & mysql_free_result() 错误

javascript - PHP 在 jQuery 中调用?

php - 如何在div中保留增加的内容

mysql - sql代码: What does it mean

php - 此 REGEXP 回显一件事,但进入 MySQL 另一件事。为什么?

php - 具有依赖项的可测试 Controller

php - 如果搜索结果不存在则隐藏表