-2
首先它工作正常但我不知道如何在此頁面中發生此錯誤,但是當我更改視圖中的代碼時可以解決此問題{{$ training- > first() - > sectionsCount}}但我的規範不正確。 我完全錯誤是: -試圖在Laravel 5.1中獲取非對象的屬性
ErrorException in Training.php line 51: Trying to get property of non-object (View:resources/views/Training/index.blade.php)
我的模型代碼是: -
public function sectionsCountRelation()
{
return $this->hasOne('App\Schedule')->selectRaw('training_id, count(*) as count')->groupBy('training_id')->where('training_end_date','<',carbon::now());
}
public function getSectionsCountAttribute()
{
return $this->sectionsCountRelation->count;<!--This is line 51 -->
}
在控制器
public function index()
{
$training = Training::with('sectionsCountRelation')->get();
return view('Training.index',compact('training'));
}
在View: - @foreach (作爲$培訓的$培訓)
<tr>
<td>{{$i}}</td>
<td>{{ $training->category }}</td>
<td>{{ $training->topic }}</td>
<td><a href="/schedule/before_held/{{$training->id}}">{{$training->sectionsCount}}</a></td>
<td><a href="{{route('training.edit',$training->id)}}" class="btn btn-info">Update</a></td>
<td><a href="/schedule/create/{{$training->id}}" class="btn btn-info">Schedule</a></td>
<td>
{!! Form::open(['method' => 'DELETE', 'route'=>['training.destroy', $training->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
<?php $i++;?>
{!! Form::close() !!}
</td>
</tr>
@endforeach
目前尚不清楚您真正要求的是什麼。但你已經給出了答案'{{$ training-> first() - > sectionsCount}}'這樣做。問題是'$ training = Training :: with('sectionsCountRelation') - > get();'返回一個集合(多個對象)而不是一個對象。所以你要麼從該集合中選擇一個對象('first()'),要麼通過該集合循環(用'for each')來顯示它們。 –