1

I have an existing table structure I'm trying to model with Eloquent (Laravel 4) which has 3 one to many relationships to the same table. Basically, each unit can have a home location, a current location and a customer's location.

Note, I've simplified this for the question. The unit table has an unitid, and a homeid, currentid and customerid. Each of homeid, currentid and customerid is a foreign key in the mysql database to the location table on the locationid. The location table also has a name field.

In my Unit model, I have

public function home() { return $this->belongsTo('Location', 'homeid', 'locationid'); }
public function current() { return $this->belongsTo('Location', 'currentid', 'locationid'); }
public function customer() { return $this->belongsTo('Location', 'customerid', 'locationid'); }

In my Location model I have

public function homes() { return $this->hasMany('Unit', 'homeid', 'locationid'); }
public function currents() { return $this->hasMany('Unit', 'currentid', 'locationid'); }
public function customers() { return $this->hasMany('Unit', 'customerid', 'locationid'); }

Now, in my Units controller I have

$units = Unit::with(['home','current','customer'])->paginate(10);
return View::make('units.index')->with('units',$units);

In units.index view I can refer to

foreach ($units as $unit) { 
...
$unit->home->name  //<-- this works
$unit->current->name //<-- this doesn't
$unit->customer->name //<-- neither does this
...
}

As fas as I can tell from the documentation, I've done everything right. Why would the first FK work, but neither of the two others?

Edit: the error given on the lines marked as not working (when uncommented) is

"Trying to get property of non-object"

DDM
  • 542
  • 4
  • 15
  • Just for debugging: please add `var_dump(DB::getQueryLog());` before returning the view, then share results – Razor Jun 30 '14 at 13:31
  • It looks like there are no related rows for some of the units. Check for `null` on the relation before echoing their names. – Jarek Tkaczyk Jun 30 '14 at 13:53
  • @deczo goddamit, it was so simple. The models were right, it was a simple null check that was needed. – DDM Jun 30 '14 at 14:05
  • Just a hint for you: http://stackoverflow.com/questions/23910553/laravel-check-if-related-model-exists#answer-23911985 – Jarek Tkaczyk Jun 30 '14 at 14:14

1 Answers1

1

The models are correct, thanks @deczo for pointing out the obvious.

The error was mine - not checking for null on the relations before trying to reference the related records.

I.E. $unit->current->name needed to be is_null($unit->curent)?'':$unit->current->name

A stupid PEBKAC error :-)

--Quog

DDM
  • 542
  • 4
  • 15