php - 如何从相关表中获取所有行,包括数据透视表中的列?
问题描述
我有 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) 的测试模型集合。
解决方案
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();
推荐阅读
- ruby-on-rails - ActionController::UnknownFormat: 新用户索引
- javascript - Leaflet L.geoJSON 可拖动
- arrays - 将目录名称和大小读入关联数组
- anaconda - 运行源激活
在 Anaconda Promt 中失败 - snowflake-cloud-data-platform - 列不匹配选项的错误在 snowsql 中不起作用
- list - 如何过滤列表
- python - 如何将高程合并到熊猫的欧几里德距离矩阵中?
- java - 当我重新打开应用程序数组列表时不存储来自 volley 的值
- graphql - 过滤或区分内置和自定义的 graphql 类型
- laravel - Laravel Passport - 将访问令牌传递给请求