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

pawan94's avatar

Fetch data from multiple tables

I have four table 1) batch table 2) student table 3) batch_student table (pivot table) 4) student_attendance.

  1. batch : id, name
  2. student : id, name
  3. batch_student: batch_id, student_id, start_date, end_date, status
  4. student_attendance: id, student_id, batch_id, attendance_status

A student can enroll in many batches and i want to fetch student attendance record based on selected batch

0 likes
2 replies
Tray2's avatar

Can you provide some example data from your tables and the desired result?

pawan94's avatar
class Batch extends Model
{
    //

    public function students()
    {
        return $this->belongsToMany('App\Models\Student')->using('App\Models\Batch_Student')->withPivot('start_date','end_date','status')->withTimestamps();
    }
class Student extends Model
{
    //
    protected $table = "students";

    public function batches()
    {
        return $this->belongsToMany('App\Models\Batch')->using('App\Models\Batch_Student')->withPivot('start_date','end_date','status')->withTimestamps();
    }

class Batch_Student extends Pivot
{
    //
    protected $table = "batch_student";

    public function student()
    {
        return $this->belongsTo('App\Models\Student');
    }
    
    public function batch()
    {
        return $this->belongsTo('App\Models\Batch');
    }
    
    public function attendance()
    {
        return $this->hasManyThrough('App\Models\Student_Attendance', 'App\Models\Batch');
    }

}

class Student_Attendance extends Model
{
    //
    protected $table = "student_attendances";

    public function students()
    {
        return $this->hasMany(
        'App\Models\Student'
        );
    }

    public function batches()
    {
        return $this->hasMany('App\Models\Batch');

    }
}

Basically i want to fetch student attendance record which is stored in student_attendance table along with student details which is stored in student table according to the selected batch.

Please or to participate in this conversation.