I have 2 tables: Buildings:
Apartments:
I also have 2 models:
Building Model
class Building extends Eloquent{
protected $table = 'buildings';
public function apartments()
{
return $this->hasMany('Apartment');
}
}
Apartment Model
class Apartment extends Eloquent{
protected $table = 'apartments';
public function building()
{
return $this->belongsTo('Building');
}
}
So now in my controller I am trying to retrieve all the apartments, and I want it joined with the Building Model so that I can retrieve the name of the building that each apartment is in.
Array('0' =>
array('id' => 1,
'building_id' => 1,
'unit_number'=>234,
'other_data'=>'other_stuff',
'name'=>'Building1'),
'1' =>
array('id' => 2,
'building_id' => 2,
'unit_number'=>567,
'other_data'=>'more_stuff',
'name'=>'Building4'))
I believe I can do this to get them independently, but how do I get them merged together?
$buildings = Building::all();
$apartments= Apartment::all();
This is what I've tried in the controller
$building = new Building();
$buildings = $building->all();
$apts = $building->find(1)->apartments();
dd($apts);
I've also tried many other variations of this in the controller with no success. Am I on the right track to retreiving the data the way I desire?
Instead of querying the models separately you can just query one and eager load the relation so they all contain that data too:
$apartments = Apartment::with('building')->get();
foreach($apartments as $apartment){
echo 'Building name: '.$apartment->building->name;
}
To get the apartments of a particular building:
$apartments = Building::find(1)->apartments;
(Note that I'm not calling the function apartments()
but accessing the property apartments
. Eloquent will then fetch the result of the relation for you)