Wednesday, March 29, 2017

Laravel Eloquent: How to select from multiple tables

I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need. I have 3 Models

  • House
  • Occupants
  • Job

A house can have multiple occupants and I can easily get these using the following.

$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();

This works nicely but I also want to select the job of each occupant. I've got this as a one to one relationship but the jobs are in a seperate table.

Is there a way to also select everything from the jobs table efficiently? I'm guessing it would be something like this

$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();



via Pattle

Advertisement