【发布时间】:2016-08-18 11:29:47
【问题描述】:
我的表之间有以下关系
在我的模型中,我有以下代码:
位置模型:
public function member() {
return $this->belongsTo('App\Member','member_id');
}
会员模型:
public function locations(){
return $this->hasMany('App\Location','member_id');
}
现在在我的位置控制器中,我创建了以下函数。
public function getFinalData(){
$locations = Location::with('member')->whereNotNull('member_id')->get();
return view('locations.final-list',['locations'=>$locations]);
}
然而,在我的刀片模板中,我无法遍历成员属性
<ul>
@foreach($locations as $location)
<li>{{$location->id}}</li>
<li>
@foreach($location->member as $member)
{{$member->id}}
@endforeach
</li>
@endforeach
</ul>
这给了我以下错误: 试图获取非对象的属性(查看:locations/final-list.blade.php)
更新:我试图达到的结果对应于这个查询
SELECT locations.location_id,locations.name,members.first_name, members.last_name , locations.meters
FROM locations,members
WHERE locations.member_id = members.id
更新 2:
所以我尝试访问一个附有单个位置的位置,并且效果很好
public function getFinalData(){
//$locations = Location::with('member')->whereNotNull('member_id')->get();
$location = Location::find(0);
return view('locations.final-list',['location'=>$location]);
}
在最终名单中 $location->member->first_name
【问题讨论】:
-
member_id 是成员表的 Pk 那么它怎么可能是 NULL 呢?你写了 whereNotNull('member_id')。
-
@RaviHirani 因为我得到了一个定义了 member_id 的位置列表?
-
我可能遗漏了一些东西,但您的方法
getFinalData似乎是错误的。当您在模型上执行with时,laravel 仅获取有关该关系的数据。它不查询关联的模型。所以在你的情况下,当你这样做$locations = Location::with('member')->whereNotNull('member_id')->get();你应该得到一个错误Column not found。