对什么应该是相当直截了当的问题感到困惑。
我有两个相互关联的物体:
class Country extends Eloquent {
public function hotspot()
{
return $this->hasOne('Hotspot');
}
}和
class Hotspot extends Eloquent {
public function country()
{
return $this->belongsTo('Country');
}
}我想找回我的热点和它们所属的国家,所以:
$hotspot_list = Hotspot::with('country')->get();作为一个测试,我只想遍历列表并输出国家代码:
foreach ($hotspot_list as $hotspot_item) {
$hotspot = $hotspot_item->country;
echo $hotspot->country_code;
}引发一个错误:“试图获取非对象的属性”。
所以很明显我也不能做echo $hotspot_item->country->country_code;
如果我以数组的形式访问$hotspot,它可以工作:echo $hotspot['country_code'];
因此,我不能作为对象访问$hotspot。因为$hotspot实际上是一个Country对象,所以我想检查我与Country之间的另一个关系,但是我做不到,因为它给了我一个数组而不是这个对象。
所以,即使我不应该这样做,我也尝试过这样做:
$country_id = $hotspot['id'];
$country = Country::find($country_id);
echo $country->name;仍然不去,它仍然作为数组返回,所以我可以做echo $country['name'];
有什么建议吗?
发布于 2014-04-04 19:37:24
确保你所有的热点都有国家,或者你可以在循环时验证它们.
foreach ($hotspot_list as $hotspot_item) {
$hotspot = $hotspot_item->country;
if(isset($hotspot->country_code)) {
echo $hotspot->country_code;
}
}或者更好的是,如果你有拉拉维尔4.1,只有那些有热点的国家.
$hotspot_list = Hotspot::has('country')->get();
https://stackoverflow.com/questions/22871111
复制相似问题