简体   繁体   English

Laravel 关系属性在此集合实例中不存在

[英]Laravel Relationship Property Does Not Exist In This Collection Instance

$category = Category::orderBy('category_name_en', 'ASC')
->get();

$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->get();

$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->get();

return view('welcome', compact('category', 'subcategory', 'subsubcategory'));

In this above code we are getting error:在上面的代码中,我们得到了错误:

Property [id] does not exist on this collection instance.此集合实例上不存在属性 [id]。

Why is this error showing?为什么会显示此错误?

That's because you are returning a Collection whenever you write get .那是因为每当你写get时,你都会返回一个Collection

Try this instead:试试这个:

$category = Category::orderBy('category_name_en', 'ASC')
->get();

$subcategory = SubCategory::whereIn('category_id', $category->pluck('id'))
->orderBy('subcategory_name_en', 'ASC')
->get();

$subsubcategory = SubSubCategory::whereIn('subcategory_id', $subcategory->pluck('id'))
->orderBy('subsubcategory_name_en', 'ASC')
->get();

return view('welcome', compact('category', 'subcategory', 'subsubcategory'));

The changes being where converted to whereIn , and ->id becomes ->pluck('id') .更改where转换为whereIn->id变为->pluck('id')

As you can see from the documentation, whereIn accepts an array of values for it's second argument, and pluck will return an array of, in our case, IDs.正如您从文档中看到的那样, whereIn接受一个值数组作为它的第二个参数,并且pluck将返回一个数组,在我们的例子中是 ID。
Combining these will mean that category_id will need to exist within the array.结合这些将意味着category_id需要存在于数组中。


If, however, these models were supposed to supply a single Model.但是,如果这些型号应该提供单个 Model。
Then you should do the following:然后,您应该执行以下操作:

$category = Category::orderBy('category_name_en', 'ASC')
->first();

$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->first();

$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->first();

return view('welcome', compact('category', 'subcategory', 'subsubcategory'));

This is using the first method to return a single instance.这是使用first一种方法返回单个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM