Laravel / 无法访问受保护的属性 Illuminate\Database\Eloquent\Collection::$items
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36980783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel / Cannot access protected property Illuminate\Database\Eloquent\Collection::$items
提问by Eben Hafkamp
I'm still learning Laravel and I'm using eloquent to run my queries. In my application a user can belong to one circle. The circle contains repositories, which in turn contains items. I am trying to fetch all of the items which belong to various repositories within one circle.
我还在学习 Laravel,我正在使用 eloquent 来运行我的查询。在我的应用程序中,一个用户可以属于一个圈子。圆圈包含存储库,而存储库又包含项目。我试图获取属于一个圆圈内的各种存储库的所有项目。
User Model:
用户模型:
public function circle () {
return $this->belongsTo('App\Models\Circle');
}
Circle Model:
圆形模型:
public function users () {
return $this->hasMany('App\Models\User');
}
public function repositories () {
return $this->hasMany('App\Models\Repository');
}
Repository Model:
存储库模型:
public function items () {
return $this->hasMany('App\Models\Item');
}
public function circle () {
return $this->belongsTo('App\Models\Circle');
}
Item Model:
商品型号:
public function repository () {
return $this->belongsTo('App\Models\Repository');
}
Here is the markup where I am trying to iterate over all items:
这是我尝试迭代所有项目的标记:
@foreach($items as $item)
<span>{{ $item->name }}</span>
@endforeach
My controller responsible for handling the route is here:
我负责处理路线的控制器在这里:
function library () {
$user = Auth::user();
$circle = $user->circle;
$repositories = $circle->repositories;
$items = $repositories->items;
return View('pages.library', compact(['user', 'circle', 'items']));
}
As of right now I can retrieve 2 repositories belonging to a circle but I cannot retrieve the multiple items that belong to those 2 repositories. I have tried a @foreach on the repositories to run through both and push the items in an empty array but I only end up with the last item. Is there a query technique/step that I'm missing?
截至目前,我可以检索属于一个圈子的 2 个存储库,但我无法检索属于这 2 个存储库的多个项目。我已经尝试在存储库上使用 @foreach 来运行两者并将项目推送到一个空数组中,但我只得到了最后一个项目。是否有我遗漏的查询技术/步骤?
采纳答案by Filip Koblański
$repositories
is a collection not a model. So you shouldn't call the $items
property prom it because it's protected.
$repositories
是一个集合而不是一个模型。所以你不应该打电话给$items
财产舞会,因为它是受保护的。
I know that You looking for the items relation so... You need to itterate over the $repositories
and the over the each $repository
$item like:
我知道您正在寻找项目关系,所以...您需要遍历$repositories
每个$repository
$item ,例如:
@foreach($repositories as $repository)
@foreach($repository->items as $item)
<span>{{ $item->name }}</span>
@endforeach
@endforeach
And remove this from the controller:
并从控制器中删除它:
$items = $repositories->items;
$items = $repositories->items;