Supunsam
Supunsam

Reputation: 379

How to get data from Multiple Tables with Laravel Eloquent

I have 2 tables called jobs & job_records. Its relationship as below:

JobRecords Model

public function job()
{
   return $this->belongsTo(Job::class);
}

Job Model:

public function jobRecord()
{
   return $this->hasOne(JobRecord::class);
}

jobs table has 2 columns that I need to display alongside my job_records table view. It's total_pges & status.

In my JobRecords Controller, I have tried the following method. It throws me an error of Call to undefined relationship.

JobRecordController:

$job_records = JobRecord::whereStatus('In Progress')
  ->with('jobs', 'jobs.status', 'jobs.total_pges')
  ->get();
return DataTables::of($job_records)

I am still beginning with Laravel and PHP. I can sense that there is something wrong with the relationship. But I couldn't figure out what it is exactly. Can anyone help me out with this matter?

Upvotes: 2

Views: 3003

Answers (2)

Jithesh Jose
Jithesh Jose

Reputation: 1814

In your JobRecord model change the relation ship as

 public function job()
 {
  return $this->hasOne('App\Models\Job','foreign_key','local_key');
 }

Similarly, in Job model

 public function job()
 {
  return $this->belongsTo('App\Models\JobRecord','foreign_key','local_key');
 }

Replace foreign_key and local_key with appropriate values...

Upvotes: 1

arkert
arkert

Reputation: 92

I deleted my previous answer. What are you trying to do exactly? You can't use "jobs" in the "with function" without to define "jobs" as function in the model.

If you change it to "job" (instead of "jobs), then it would work, but I don't know if you want this. With your query you saying that a record have many jobs? But your model doesn't define that.

Upvotes: 0

Related Questions