控制器函数(应该返回2个结果,以及它们的位置和消息计数):
public function getIndex()
{
$alerts = User::with('alerts.location')
->where('id', '=', Auth::user()->id)->get();
$this->layout->content = View::make('agents.index',
array('alerts' => $alerts));
}
用户型号:
public function alerts()
{
return $this->hasMany('Alert');
}
警报型号:
public function location()
{
return $this->belongsTo('Location');
}
public function user()
{
return $this->belongsTo('User');
}
public function messages()
{
return $this->hasMany('Message');
}
视图:
@foreach($alerts as $alert)
<tr>
<td>{{ $alert->location->address_1}}</td>
<td>{{ $alert->location->address_2}}</td>
<td>{{ $alert->location->address_3}}</td>
<td>{{ $alert->location->postcode}}</td>
<td>{{ $alert->messages->count()}}</td>
</tr>
@endforeach
任何试图访问location
或messages
的回波都失败-
ErrorException尝试获取非对象的属性
我将查询从->first()方法更改为->get()方法,这就是问题的根源。每个警报肯定有多条消息和一个与之相关的位置。
看起来$alerts是一个User数组,而您将其用作Alert数组。试试这个:
$alerts = User::with('alerts.location')
->where('id', '=', Auth::user()->id)->first()->alerts;
get()的问题是它返回一个数组,即使有0或1个结果,而且似乎只期望一个结果。
$alerts = User::with('alerts.location')->where('id', '=', Auth::user()->id)->get();
上面一行返回了一个用户模型的Eloquent Collection,该模型具有急切加载的嵌套关系,但没有像您希望的那样发出警报,并且您在这里没有急切加载消息,因此您将在foreach循环中面临n+1问题。此外,您已经在Auth::user()中加载了user,因此无需再次查询users表。
相反,使用这个:
$alerts = Auth::user()->alerts // this loads all alerts as a Collection
->load('location') // here we eager load related Location for every Alert
->load('messages'); // and here we eager load related messages for all Alerts
// now $allerts is a Collection of Alert models and related Local models
// so this will work (Still add some check for ->location as it might be null
// if there is no related location for an alert):
@foreach($alerts as $alert)
<tr>
<td>{{ $alert->location->address_1 }}</td>
<td>{{ $alert->location->address_2 }}</td>
<td>{{ $alert->location->address_3 }}</td>
<td>{{ $alert->location->postcode }}</td>
<td>{{ $alert->messages->count() }}</td>
</tr>
@endforeach