在我的路线中,我将此路线定义为:
// app/routes.PHP Route::resource('CharacterController');
控制器中的相应方法是:
// app/controllers/CharacterController.PHP public function index(){ $characters = Character::all(); $houses = House::all(); return View::make('characters.index')->with(array('characters'=>$characters,'houses' => $houses)); }
最后,在视图中:
// app/views/characters/index.blade.PHP #this fires an error: {{ $houses[$characters->house_id]->name }} # at the same time this gives correct result: {{ $houses[1]->name }} # and this IS equal to 1: {{ $characters->house_id }}
解决方法
您不能使用id作为数组的索引来访问具有给定id的对象.
由于您拥有Eloquent Collection,因此您可以使用其各种功能.其中一个是find(),用于通过id检索一个项目
{{ $houses->find($characters->house_id)->name }}