Как использовать свойство Модели в отношениях красноречивых запросов

#laravel #eloquent #eloquent-relationship

Вопрос:

У меня есть три Модели. Университет, профессор и студент. У них есть какие-то отношения.

  1. Модель Университета :
 lt;?php  namespace AppModels;  use IlluminateDatabaseEloquentModel; use AppModelsUser;  class University extends Model {  protected $fillable = ['name', 'user_id'];   /**  * Get the user that owns the university.  */  public function owner()  {  return $this-gt;belongsTo(User::class);  } }  
  1. Профессор Модель :
 lt;?php  namespace AppModels;  use IlluminateDatabaseEloquentModel; use AppModelsUniversity; use AppModelsStudent;  class Professor extends Model {  protected $fillable = ['name', 'surname', 'university_id'];   /**  * Get the university where the professor teaches.  */  public function university()  {  return $this-gt;belongsTo(University::class);  }   /**  * Get the student associated with the professor.  */  public function student()  {  return $this-gt;hasOne(Student::class)-gt;withDefault();  } }  
  1. Студенческая Модель :
 lt;?php  namespace AppModels;  use IlluminateDatabaseEloquentModel; use AppModelsUniversity; use AppModelsProfessor;  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-gt;belongsTo(University::class);  }   /**  * Get the professor of the student.  */  public function professor()  {  return $this-gt;belongsTo(Professor::class);  } }  

Каждый профессор принадлежит к университету. Каждый студент принадлежит к университету. У каждого студента есть ровно один профессор, но у профессора может не быть студента.

Вопрос : Как у меня может быть список студентов, которые учатся в одном университете со своим профессором?

Следующий код неверен!

 $students = Student::select('id', 'name', 'surname', 'age', 'university_id') -gt;whereRelation('professor', 'university_id', '=', ***'student.university_id'***)  -gt;with(['university', 'professor']) -gt;orderBy('id', 'desc') -gt;paginate(20);  

Спасибо.

Комментарии:

1. в каком случае студент будет учиться в другом университете, чем его профессор?

2. может быть, приглашенный профессор в университете

Ответ №1:

Если вы передадите $universityId, вам следует следовать 1-му примеру. В противном случае вы можете получить всех студентов, сгруппировав university_id

1-й пример:

 $students = Student::with(['university', 'professor'])  -gt;where('university_id', '=', $universityId)  -gt;orderBy('id', 'desc')  -gt;paginate(20);  

2-й пример:

 $students = Student::with(['university', 'professor'])  -gt;groupBy('university_id')  -gt;orderBy('id', 'desc')  -gt;paginate(20);