从Blade模板查询外键数据 [英] Query foreign key data from Blade template
问题描述
MenuCategory
和 MenuItem
,我想在我的刀片页面上显示MenuItem数据其MenuCategory。我知道它可以通过将其添加到控制器中的返回数据来实现,但是我想用Eloquent来代替,但是我收到错误。 这里是我的代码:
MenuCategory模型
public function items()
{
return $ this-> hasMany('App \MenuItem');
}
MenuItem模型
public function category()
{
return $ this-> belongsTo('App \MenuCategory');
}
控制器
public function show($ id)
{
$ item = MenuItem :: findOrFail($ id);
return view('menu.admin.single',compact('item'));
}
刀片页
{{$ item-> category-> name}}
更新:
表 menu_item >
id
name
menu_category_id
表 menu_category
id
name
当使用上述所有内容时,我会收到以下错误:
尝试获取非对象的属性
在关系方法中提供可选的外键变量以使其正常工作,即
$ this-> belongsTo('App \MenuCategory','menu_category_id');
I have two models: MenuCategory
and MenuItem
, I want to display MenuItem data on my blade page along with its MenuCategory. I know its possible to do this by adding it to the return data in my controller however I would like to do it leveraging Eloquent instead, however I receive errors.
Here are my codes:
MenuCategory model
public function items()
{
return $this->hasMany('App\MenuItem');
}
MenuItem model
public function category()
{
return $this->belongsTo('App\MenuCategory');
}
Controller
public function show($id)
{
$item = MenuItem::findOrFail($id);
return view('menu.admin.single', compact('item'));
}
Blade Page
{{ $item->category->name }}
UPDATE:
Table menu_item
id
name
menu_category_id
Table menu_category
id
name
When using all the above I get the following error:
Trying to get property of non-object
This error is due to the naming convention of Eloquent.
Provide the optional foreign key variable in your relationship method to make it work, ie.
$this->belongsTo('App\MenuCategory', 'menu_category_id');
这篇关于从Blade模板查询外键数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!