![](/img/trans.png)
[英]Property [X] does not exist on this collection instance laravel relationship
[英]Laravel HasManyThrough Returns Property [X] does not exist on this collection instance
我实际上设法从 HasManyThrough 关系中获取数据,但是当我想访问关系数据时,它会引发错误:
Property [publishings] does not exist on this collection instance.
(View: C:\Xampp\htdocs\wave\resources\views\pages\category.blade.php)
如下图所示,我收到了“出版物”数据。
我从哪里得到错误的是这个 Blade 文件:
类别.blade.php
@foreach ($data->publishings as $item)
<div></div>
@endforeach
由于我有数据,下面的代码对于解决方案可能是不必要的,但它们在那里,以防万一。
类别控制器.php
public function index($category)
{
$data = Category::where('slug', $category)
->with(['publishings' => function ($query) {
$query->where('slug', '!=', 'placeholder')->latest()->paginate(10);
}])->get();
return view('pages.category')->with('data', $data);
}
分类.php
public function assets()
{
return $this->hasMany('App\Models\Asset');
}
public function publishings()
{
return $this->hasManyThrough('App\Models\Publishing', 'App\Models\Asset');
}
资产.php
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function publishings()
{
return $this->hasMany('App\Models\Publishing');
}
发布.php
public function asset()
{
return $this->belongsTo('App\Models\Asset');
}
谢谢你的帮助。
如果有人遇到同样的问题并遇到此消息,则解决方案,就我而言,实际上非常简单。 图片中的第三行说:
0 => App\Models\Category
我试图访问关系数据,就好像 $data 是一个对象一样。 这就是为什么
$data->publishings
抛出错误。 解决方案是
$data[0]->publishings
或者仅从控制器返回该数据:
return view('pages.category')->with('data', $data[0]);
您正在将 Eloquent Collection 传递给视图。 如果只想查询第一个结果,可以使用查询生成器的first()
方法而不是get()
:
public function index($category)
{
$data = Category::where('slug', $category)
->with(['publishings' => function ($query) {
$query->where('slug', '!=', 'placeholder')->latest()->paginate(10);
}])->first();
return view('pages.category')->with('data', $data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.