【发布时间】:2022-01-05 17:03:09
【问题描述】:
我有三个模型。大学,教授和学生。 他们有一些关系。
- 大学模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class University extends Model
{
protected $fillable = ['name', 'user_id'];
/**
* Get the user that owns the university.
*/
public function owner()
{
return $this->belongsTo(User::class);
}
}
- 教授型号:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\University;
use App\Models\Student;
class Professor extends Model
{
protected $fillable = ['name', 'surname', 'university_id'];
/**
* Get the university where the professor teaches.
*/
public function university()
{
return $this->belongsTo(University::class);
}
/**
* Get the student associated with the professor.
*/
public function student()
{
return $this->hasOne(Student::class)->withDefault();
}
}
- 学生模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\University;
use App\Models\Professor;
class Student extends Model
{
protected $fillable = ['name', 'surname', 'age', 'university_id', 'professor_id'];
/**
* Get the university where the student is studying.
*/
public function university()
{
return $this->belongsTo(University::class);
}
/**
* Get the professor of the student.
*/
public function professor()
{
return $this->belongsTo(Professor::class);
}
}
每位教授都属于一所大学。 每个学生都属于一所大学。 每个学生只有一位教授,但一位教授可能没有学生。
问题: 如何获得与教授在同一所大学的学生名单?
以下代码不正确!
$students = Student::select('id', 'name', 'surname', 'age', 'university_id')
->whereRelation('professor', 'university_id', '=', ***'student.university_id'***)
->with(['university', 'professor'])
->orderBy('id', 'desc')
->paginate(20);
谢谢。
【问题讨论】:
-
在什么情况下学生与教授在不同的大学?
-
也许是大学的客座教授
标签: laravel eloquent eloquent-relationship