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

Prabodhana's avatar

get details using foreignkey using another table foreginkey

I have three tables in my database

  1. tbl_universities [id, code, name, country]
  2. tbl_programs [id, tbl_university_id, program],
  3. tbl_batches [id, tbl_program_id],

in tbluniversity model has this relationship

public function programs(){
        return $this->hasMany(tblProgram::class,"tbl_university_id","id");
    }

in tblprogram model has this relationship

public function univesity(){
        return $this->belongsTo(tblUniversity::class,"tbl_university_id","id");
    }

public function batch(){
        return $this->hasMany(tblBatch::class,"tbl_program_id","id");
    }

in tblbatch model has this relationship

public function program(){
        return $this->belongsTo(tblProgram::class,"tbl_program_id","id");
    }

in my controller using this code I can get batch details and program details

public function batchGet(){
        $uni = tblBatch::with('program')->get();        
        return BatchRegResource::collection($uni);
    }

I want to know is there any way to get university details also for that batch belong using this these relationship?

Thank You....

0 likes
3 replies
BintuGomes's avatar

Background: I took a very basic Info Systems class in college that had a section on Access, so I understand a little about databases, Primary Keys, and one-to-many, many-to-one, etc. relationships. I have also taken MITx 6.00x and most of LPTHW. I am currently taking Django's poll tutorial. https://9apps.ooo

My question is about Foreign Keys. Im not really sure what they are doing and why they are necessary. I'm at the end of the first section of the Django tutorial and trying to get a good understanding of the API. This is the things that is really confusing me. https://solitaire.onl/

kingshark's avatar
Level 2

How do you want to display the data?

if you want uni data nested into each program like this:

[{id:x, program: {id: y, uni: {id: z} } }, ...]

then just tblBatch::with('program.univesity')->get();

1 like

Please or to participate in this conversation.