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

insight's avatar

How to join two tables using Eloquent ?

Dear Friends,

I have 2 tables need to join .

  1. 'local_bodies' with structure

lbid integer NOT NULL, lbname_mal character varying(50)

  1. 'requested_stations' with structure

id integer NOT NULL DEFAULT nextval('ulbgt_requested_stations_id_seq'::regclass), requested_station integer NOT NULL, option_number smallint NOT NULL

Here these two tables need to join . One person can 'request' 3 requested stations with 'option number 1,2,3'.

I have relation model for 'local_bodies' as

         public function requestedstation()
    {
       return $this->hasMany('App\Ulbgt\LocalBody','lbid');
    }

for 'requested_stations' as

           public function localbody()
    {
      return $this->belongsTo('App\Ulbgt\LocalBody','id');
    }

I wrote query using eloquent as

           $requested_station = RequestedStation::with(['localbody' => function ($qry) {
                                                $qry->select('lbid','lbname_mal');
                                     }])->select('id','requested_station','option_number')->get();

but got wrong result for 'lbname_mal'.

Please advise ... I suspect some problem in query or relation model

Waiting fast reply

Thanks

0 likes
2 replies
SyedAbuthahir's avatar
// This line fetch the datas. There's no need for select and get.
 $requested_station = RequestedStation::with(['localbody'])->get();

Snapey's avatar

Too hard to comprehend...

You can't have the same model name in both relationships?

What are your models called and what is the foreign key linking them. Is it one to one or one to many?

Please or to participate in this conversation.