dsyq40772 2017-09-17 13:34
浏览 39

如何在Laravel中将采集结果作为一个集合

So I am working on a RESTApi with Laravel.

I am trying to get all the products that the buyer has bought. The thing is that buyer and products they are related through transactions table. Now the code below I am getting the results needed back since I am using Laravel eagerloading to get transactions with their products like so:

     /**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index(Buyer $buyer)
{

    $products = $buyer->transactions()->with('product')->get()->pluck('products');



    return $this->showAll($products);
}

The thing here is that I have a trait that is being called on my base ApiController that trait has a method showAll() to return/display a json response of the request. The showAll() method expects a collection to be returned. While I am sending a property of a collection instead.

My question:
How do I get back the products after eagerloading as collections instead of property ?

  • 写回答

1条回答 默认 最新

  • douzai8285 2017-09-17 14:35
    关注

    You could use the collect()helper function to convert your $products array to collection.

    Refer more on the doc https://laravel.com/docs/5.5/collections#introduction

    评论

报告相同问题?

悬赏问题

  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区