【问题标题】:Eloquent model with multiple one to many to same table具有多个一对多到同一个表的雄辩模型
【发布时间】: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


【解决方案1】:

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

错误是我的 - 在尝试引用相关记录之前未检查关系是否为空。

I.E. $unit->current->name 需要是 is_null($unit->curent)?'':$unit->current->name

一个愚蠢的PEBKAC错误:-)

--魁格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多