【发布时间】:2014-06-30 12:36:19
【问题描述】:
我有一个现有的表结构,我正在尝试使用 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 控制器中
$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 行得通,而其他两个都行不通?
编辑:在标记为不工作(未注释时)的行上给出的错误是
"试图获取非对象的属性"
【问题讨论】:
-
调试用:返回视图前请加
var_dump(DB::getQueryLog());,然后分享结果 -
有些单元似乎没有相关行。在呼应他们的名字之前检查关系上的
null。 -
@deczo 该死,就是这么简单。模型是正确的,需要进行简单的空值检查。
标签: php mysql laravel laravel-4 eloquent