Querying a table and its relationship, and using the relationship to query related records
I am using Laravel 5.6 and mysql. I have a Tasks table that has a StudentID column linked to the primary key StudentID in the StudentInfo table. Each student in the StudentInfo table has a IDNumber column which is unrelated to the StudentID. I query all tasks, and also the students who were assigned to that ask.
One student can have many tasks, but a task only has one student. The end user may accidentally create a new student and assign them to a task not knowing they exist. It is not possible to let the end user that the student already exists at the time they are assigning a student to a task, or include the IDNumber in the Tasks table..
What is a cleaner and more efficient way of doing this?
Tasks
-StudentID
StudentInfo
-StudentID
-IDNumber
Tasks model
public function student() {
return $this->belongsTo(StudentInfo::class, 'studentID', 'id');
}
StudentInfo model
public function tasks(){
return $this->hasMany(Tasks::class, 'studentID', 'id');
}
querying all sessions including the StudentInfo
$tasks = Tasks::where('status', null)->with(['office.info', 'student'])->get();
foreach ($tasks as $task) {
$tasks->matches = StudentInfo::where('idNumber', '=', $task->student["idNumber"])->get();
}
Please or to participate in this conversation.