我有2个表,分区和地址。假设这两个表之间有相互关系。 地址表包含分区外键。问题是它在视图中返回null。如何显示/输出地区名称?我完全根据Laravel文档遵循了该指令。
DISTRICT TABLE
区域模型
public function address()
{
return $this->hasOne('App\Address');
}
ADDRESS TABLE
地址模型
public function district()
{
return $this->belongsTo('App\District', 'district');
}
查看
$getAddress = App\Address::all();
foreach($getAddress as $add)
{
Address name: {{ $add->address_name }}
District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}
答案 0 :(得分:3)
相反,您应该使用with
$getAddress = App\Address::with('district')->all();
获得价值
{{ $add->district->district_name }}
答案 1 :(得分:0)
你应该试试这个:
<php $getAddress = App\Address::with('district')->get(); ?>
@foreach($getAddress as $add)
Address name: {{ $add->address_name }}
@foreach($add->district as $districrt)
District name : {{ $districrt->district_name }}
@endforeach
@endforeach