我有这些桌子:
table: investigation
id
name
start_city
end_city
table: city
id
name表start_city和end_city指的是city.id。
这是我的Investigation模型:
public function start_city(){
return $this->hasOne('City', 'id', 'start_city');
}
public function end_city(){
return $this->hasOne('City', 'id', 'end_city');
}City模型:
public function start_city(){
return $this->belongsTo('Investigation', 'id', 'start_city');
}
public function end_city(){
return $this->belongsTo('Investigation', 'id', 'end_city');
}Investigation控制器:
public function show($id){
echo '<pre>';
var_dump(Investigation::find($id)->start_city->name);
}我总是得到Trying to get property of non-object。我怀疑这段关系在某种程度上已经“破裂”了。我该怎么解决这个问题?我试着切换hasOne和belongsTo,但这并没有改变任何事情。
PS:请不要评论代码惯例,因为我把这段代码从没有复数形式的其他语言中“翻译”出来。
发布于 2014-10-07 16:59:44
把你所有的关系重新命名为camelCase
public function startCity(){
return $this->hasOne('City', 'id', 'start_city');
}
public function endCity(){
return $this->hasOne('City', 'id', 'end_city');
}其他车型也是如此。
然后您可以使用dynamic properties,如下所示:
$investigation->startCity;否则,您就不能使用动态属性,您需要这样做:
$investigation->start_city()->getResults()->name;https://stackoverflow.com/questions/26241107
复制相似问题