Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

derrickrozay's avatar

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();
 }
0 likes
0 replies

Please or to participate in this conversation.