本文介绍了该集合实例上不存在属性[subcategory]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一次使用雄辩
关系.我正在尝试访问 subcategory方法
,但出现此错误:
First time working with eloquent
relationship. I'm trying to access the subcategory method
yet I get this error:
laravel的新手,所以将不胜感激!
New to laravel so any help would be appreciated!
刀片
<table class="table">
<thead>
<tr>
<th scope="col">Category</th>
<th scope="col">Sub-category</th>
</tr>
</thead>
<tbody>
@foreach ($categories as $cat)
<tr>
<td scope="row">{{$cat->name}}</td>
//error here
@foreach ($categories->subcategory as $item)
<td>{{$item->name}}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
类别模型
class Category extends Model
{
protected $fillable = ([
'name'
]);
public function subcategory(Type $var = null)
{
# code...
return $this->hasMany(Subcategory::class,'category_id','id');
}
}
子类别模型
class子类别扩展了Model{受保护的$ fillable =(['category_id','名称']);
class Subcategory extends Model{ protected $fillable = ([ 'category_id', 'name' ]);
public function category(Type $var = null)
{
# code...
return $this->belongsTo(Category::class);
}
}
控制器
public function create()
{
$categories = Category::all();
// dd($categories);
return view('settings.create', compact('categories'));
}
推荐答案
在foreach循环中您做错了.您的第二个foreach循环将类似于
You are doing wrong in foreach loop. Your second foreach loop will be like
@foreach ($categories as $cat)
<tr>
<td scope="row">{{$cat->name}}</td>
@foreach ($cat->subcategory as $item)
<td>{{$item->name}}</td>
@endforeach
</tr>
@endforeach
您当前的对象是 $ cat
,而 $ categories
是一个集合.
your current object is $cat
and $categories
is a collection.
这篇关于该集合实例上不存在属性[subcategory]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!