【发布时间】:2019-09-24 07:10:54
【问题描述】:
我正在尝试显示按类别分组的餐厅菜单,例如...
- 午餐
- 鸡肉和薯条
- 大米
- 早餐
- 茶
- 咖啡
所以我的数据库中有 3 个表,餐厅、类别和菜单
类别型号
class Category extends Model
{
protected $fillable = [
'name'
];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function menus_type()
{
return $this->hasMany('App\Menu','category_id');
}
}
菜单模型
class Menu extends Model
{
protected $fillable = [
'name',
'price',
'description',
'photoPath',
'restaurant_id',
'category_id',
];
/**
* Menu belongs to Restaurant
*/
public function restaurant()
{
return $this->belongsTo('App\Restaurant');
}
/**
* Menu belongs to category type
*/
public function category_type()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
餐厅管理员
public function show($slug, RestaurantRepository $repository){
if(! $restaurant = $repository->get(['slug' => $slug], with(['cuisines','user', 'photos', 'thumbs', 'region', 'ratings.user']))) return abort('404');
$menus=Menu::with(['category_type'])->where('restaurant_id',$restaurant->id)->get()->groupBy('category_id');
return view('frontend.restaurant.show', compact('restaurant', 'p','menus'));
}
当我转储时,它看起来还不错。
结果已分组
现在我的问题出在 View 上,当我尝试获取此结果时出现错误。
@if($menus)
<ul>
@foreach($menus as $m)
<li>
{{$m->name}}
</li>
@endforeach
</ul>
@endif
ErrorException (E_ERROR)。
此集合实例上不存在属性 [名称]。
【问题讨论】:
-
当你循环遍历
$menus时,$m本身不是一个集合数组吗? -
另外,
Menu属性中没有name。 -
在
groupBy('category_id')laravel.com/docs/5.8/collections#method-toarray之后添加->toArray() -
看看你的目标,当你在视图中循环时可以利用关系的动态属性时,groupBy() 似乎是多余的。
标签: php laravel laravel-5 eloquent