【问题标题】:Resource in LaravelLaravel 中的资源
【发布时间】:2019-12-04 11:17:10
【问题描述】:

产品控制器


API 路由


错误

我得到错误:

错误异常 (E_NOTICE) 未定义的属性:Illuminate\Database\Query\Builder::$name" 当我在浏览器中使用链接运行 Laravel 应用程序时:http://127.0.0.1:8000/api/products!

帮我解决这个bug非常感谢(我是学习Laravel的新手,谢谢!!!)]

【问题讨论】:

  • 分享你的代码。
  • 您好,您可以通过文本粘贴您的代码 sn-ps。图片是额外的。您也可以在代码的开头使用 3 个符号“`”和结尾的 3 个“`”来格式化代码。
  • 带有函数索引的控制器: public function index() { return ProductCollection::collection(Product::all()); }
  • 和 ProductCollection 中的代码: public function toArray($request) { return [ 'name' => $this->name, 'totalPrice' => round( (1- ($this->discount /100))*$this->price,2), 'rating' => $this->reviews->count()> 0 ?round($this ->reviews->sum('star')/$this ->reviews->count(),2) :'No rating yet', 'href' => [ 'link' => route('products.show',$this->id) ] ]; }

标签: php laravel


【解决方案1】:

您以错误的方式访问数据,例如 ProductCollection 中的$this->name

正如 Laravel 文档中的 here 所述, 您必须通过 $this->collection 属性访问您的属性,该属性填充了集合中每个项目的映射。

尝试使用:

$this->collection->name 你应该没事。

【讨论】:

  • Tks 但我的错误仍然显示相同。未定义的属性:Illuminate\Database\Query\Builder::$name
  • 在 laravel 中,有没有其他方法可以使用资源而不是集合?什么时候使用资源,什么时候在 laravel 中使用集合?谢了!
  • 感谢您的建议安德里亚坎帕纳。我从 Laravel 的主页上找到了一些建议!然后我尝试了: $this->collection->get() 一切看起来都不错;但我仍在搜索,我会尝试找到正确使用它的方法。如果您对此有很好的标准和解释,请与我分享,非常感谢
  • 我在这里找到一个帖子:stackoverflow.com/questions/46388205/….
猜你喜欢
  • 1970-01-01
  • 2019-08-04
  • 2020-06-13
  • 2020-03-23
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
相关资源
最近更新 更多