调用 belongsTo return null laravel
invoke belongsTo return null laravel
数据库中的table是
地址
'address_type_id',
'address_type_id',
'line1',
'line2',
'line3',
'country',
'city',
'zip_code',
'other_detail',
'geo_location_id'
地址类型table
'address_type_id'
'address_type_name'
这是我的模型
public function Users(){
return $this->hasOne('User','address_id');
}
public function Address_Type(){
return $this->belongsTo('Address_Type','address_type_id','address_type_id');
}
public function Geo_Location(){
return $this->belongsTo('Geo_Location','geo_location_id','geo_location_id');
}
}
public function Address(){
return $this->hasMany('Address','address_type_id','address_type_id');
}
}
在控制器中
当我尝试获取这样的地址类型时
$address1=Address::find(1);
$geo=$address1->Geo_Location;
return Response::json(
array(
'error' => false,
'Address_Type' =>$address1->Address_Type),
200
);
});
结果 returns null
问题是关系方法的命名。执行 $address1->Address_Type
时会发生以下情况:
首先,调用 Illuminate\Database\Eloquent\Model
中的 __get()
,它代理到 getAttribute()
。在那里它首先检查一些其他的东西然后是这个:
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
如您所见,属性名称 Address_Type
已转换为驼峰命名法。变成 addressType
.
现在 PHP 不关心它是 AddressType
还是 aDdReSsTyPe
下划线会有所不同。
解决方案
更改您的关系名称。我建议 addressType
, geoLocation
但正如我之前提到的,唯一重要的是你失去了 _
.
数据库中的table是 地址 'address_type_id', 'address_type_id', 'line1', 'line2', 'line3', 'country', 'city', 'zip_code', 'other_detail', 'geo_location_id'
地址类型table 'address_type_id' 'address_type_name'
这是我的模型
public function Users(){
return $this->hasOne('User','address_id');
}
public function Address_Type(){
return $this->belongsTo('Address_Type','address_type_id','address_type_id');
}
public function Geo_Location(){
return $this->belongsTo('Geo_Location','geo_location_id','geo_location_id');
}
}
public function Address(){
return $this->hasMany('Address','address_type_id','address_type_id');
}
}
在控制器中 当我尝试获取这样的地址类型时
$address1=Address::find(1);
$geo=$address1->Geo_Location;
return Response::json(
array(
'error' => false,
'Address_Type' =>$address1->Address_Type),
200
);
}); 结果 returns null
问题是关系方法的命名。执行 $address1->Address_Type
时会发生以下情况:
首先,调用 Illuminate\Database\Eloquent\Model
中的 __get()
,它代理到 getAttribute()
。在那里它首先检查一些其他的东西然后是这个:
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
如您所见,属性名称 Address_Type
已转换为驼峰命名法。变成 addressType
.
现在 PHP 不关心它是 AddressType
还是 aDdReSsTyPe
下划线会有所不同。
解决方案
更改您的关系名称。我建议 addressType
, geoLocation
但正如我之前提到的,唯一重要的是你失去了 _
.