Laravel提出了关于在2个表之间使用One to One关系的问题

时间:2017-11-15 06:04:59

标签: php mysql laravel

我有2个分区地址。假设这两个表之间有相互关系。 地址表包含分区外键。问题是它在视图中返回null。如何显示/输出地区名称?我完全根据Laravel文档遵循了该指令。

DISTRICT TABLE

enter image description here

区域模型

public function address()
{
    return $this->hasOne('App\Address');
}

ADDRESS TABLE

enter image description here

地址模型

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?
}

2 个答案:

答案 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