雄辩的模型,具有多个一对多到同一个表

时间:2014-06-30 12:36:19

标签: php mysql laravel laravel-4 eloquent

我有一个现有的表结构我试图用Eloquent(Laravel 4)建模,它与同一个表有3个一对多的关系。基本上,每个单元可以有一个家庭位置,一个当前位置和一个客户的位置。

注意,我已经针对这个问题对此进行了简化。单位表有一个unitid,一个homeid,currentid和customerid。 homeid,currentid和customerid中的每一个都是mysql数据库中locationid上位置表的外键。位置表还有一个名称字段。

在我的单元模型中,我有

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'); }

在我的位置模型中,我有

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'); }

现在,我的单位控制器中有

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

在units.index视图中,我可以参考

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

我从文档中可以看出,我已经做好了一切。为什么第一个FK会起作用,但是其他两个都没有?

编辑:标记为不起作用的行(未取消注释时)上给出的错误是

&#34;试图获得非对象的属性&#34;

1 个答案:

答案 0 :(得分:1)

模型是正确的,感谢@deczo指出显而易见的。

错误是我的 - 在尝试引用相关记录之前没有检查关系上的null。

即。 $ unit-&gt; current-&gt;名称需要为is_null($ unit-&gt; curent)?&#39;&#39;:$ unit-&gt; current-&gt; name

一个愚蠢的PEBKAC错误: - )

- Quog