简体   繁体   中英

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?

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM