我正在尝试通过存储在用户表中的ID根据用户的相应地区/区域来获取用户
我能够获取District的结果,而Area却出错了,
试图获取非对象的属性“ area_name”(查看: user-index.blade.php)
User
id | district_id | area_id | user_name
District
id | district_name
area
id | district_id | area_name
控制器
$users = Users::simplePaginate(5);
return view('user-index',compact('users'));
模型
用户
public function districts(){
return $this->belongsTo('App\Districts','district_id','id');
}
public function areas(){
return $this->belongsTo('App\Area','area_id','id');
}
刀片
@foreach ($users as $user)
{{$user-> first_name}} - I get result
{{$user->districts->district_name}} - I get result
{{$user->areas->area_name}} -- I get error
@endforeach
答案 0 :(得分:4)
在您的控制器中尝试:
$users = Users::with('areas')->with('districts')->simplePaginate(5);
return view('user-index',compact('users'));
编辑答案:
在用户模型中:
public function districts() {
return $this->belongsTo('App\Districts','district_id','id');
}
在地区模型中:
public function areas() {
return $this->belongsTo('App\Area','district_id','id');
}
然后在您的 Controller 中,您将获取如下关系:
$users = Users::with('districts.areas')->simplePaginate(5);
return view('user-index',compact('users'));
我希望这会有所帮助。
答案 1 :(得分:2)
尝试使用控制器
$users = Users::with(['areas','districts'])->simplePaginate(5);
return view('user-index',compact('users'));
在刀片文件中是否设置了检查关系。
@foreach ($users as $user)
{{ $user->first_name }}
{{ $user->districts ? $user->districts->district_name : '' }}
{{ $user->areas ? $user->areas->area_name : '' }}
@endforeach
答案 2 :(得分:1)
发生错误,因为同一用户没有区域。要修复它,请使用此
@foreach ($users as $user)
{{$user->first_name}}
{{$user->districts->district_name ?? ''}}
{{$user->areas->area_name ?? ''}}
@endforeach
或
@foreach ($users as $user)
{{$user-> first_name}}
@if($user->districts)
{{$user->districts->district_name}}
@endif
@if($user->areas)
{{$user->areas->area_name}}
@endif
@endforeach
对于属于关系,也使用单数名称
public function district(){
return $this->belongsTo('App\Districts','district_id','id');
}
public function area(){
return $this->belongsTo('App\Area','area_id','id');
}
在刀片中使用的情况
@foreach ($users as $user)
{{$user->first_name}}
{{$user->district->district_name ?? ''}}
{{$user->area->area_name ?? ''}}
@endforeach
为避免在控制器中延迟加载
$users = Users::with(['area', 'district'])->simplePaginate(5);
return view('user-index',compact('users'));