首页 > 解决方案 > 如何从相关表中获取所有行,包括数据透视表中的列?

问题描述

我有 2 个表(学生、测试)和一个数据透视表(student_test)。从特定学生那里,我想从测试中获取所有行,包括来自 student_test 的相关列。如果没有测试结果,student_test 列的值为 NULL。

我试图这样做:

public function all_tests()
{
    $collection = new Collection();

    foreach (Tests::all() as $test) {
        if (($model = $this->tests->find($test->id)) === null) {
            $model = $test;
        }

        $collection->push($model);
    }

    return $collection;
}

我有以下型号。

应用程序/Http/Models/Student.php:

class Student extends Model
{
    protected $table = 'students';

    // Attributes: id, first_name, last_name

    public function tests()
    {
        return $this->belongsToMany(Test::class);
    }
}

应用程序/Http/Models/Test.php:

class Student extends Model
{
    protected $table = 'tests';

    // Attributes: id, name

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

我想从 student_test 表中返回带有额外列 (test_result) 的测试模型集合。

标签: phplaraveleloquent

解决方案


Laravel 仅使用该表student_test从测试表或学生表中获取模型,它不考虑任何额外的列。

我认为您需要一个额外的模型,该模型Result与测试具有多对一关系,与学生具有一对多关系

添加带有结果列的模型

将此添加到Student模型中

public function results()
{
     return $this->hasMany(Result::class);
}

将此添加到Test模型中

public function results()
{
     return $this->hasMany(Result::class);
}

将此添加到Result模型中

public function test()
{
     return $this->belongsTo(Test::class);
}

public function student()
{
     return $this->belongsTo(Student::class);
}

并添加正确的列。

这样你就可以做到:

$student->results->whereHas('test', function ($query) use ($test) {
    $query->where('id', '=', $test->id);
})->get();

或者:

$test->results->whereHas('student', function ($query) use ($student) {
        $query->where('id', '=', $student->id);
})->get();

推荐阅读