laravel - 传递给 App\Http\Controllers\ApiController::showAll() 的参数 1 必须是 Illuminate\Database\Eloquent\Collection 的实例
问题描述
我想检索特定卖家的所有买家。当我删除 pluck 和 get 方法后链接的其他方法时,它正在工作。但不是我想要的确切的东西。我该如何解决这个问题?
<?php
namespace App\Http\Controllers\Seller;
use App\Http\Controllers\ApiController;
use App\Seller;
use Illuminate\Http\Request;
class SellerBuyerController extends ApiController
{
public function index(Seller $seller)
{
$buyers = $seller->products()
->whereHas('transactions')
->with('transactions.buyer')
->get()->pluck('transactions')
->collapse()->pluck('buyer')
->unique('id')
->values();
return $this->showAll($buyers);
}
protected function showAll(Collection $collection, $code = 200)
{
return $this->successResponse($collection, $code);
}
protected function successResponse($data, $code)
{
return response()->json($data, $code);
}
}
卖家模型与产品有很多关系
<?php
namespace App;
use App\Scopes\SellerScope;
class Seller extends User
{
public function products()
{
return $this->hasMany(Product::class);
}
}
产品模型与交易有很多关系
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'name', 'description', 'quantity', 'status', 'image', 'seller_id',
];
public function transactions()
{
return $this->hasMany(Transaction::class);
}
}
交易模式和与买方的关系
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Transaction extends Model
{
use SoftDeletes;
protected $fillable = [
'quantity', 'buyer_id', 'product_id'
];
public function buyer()
{
return $this->belongsTo(Buyer::class);
}
}
解决方案
您在顶部缺少导入:
use Illuminate\Support\Collection;
否则它假定Illuminate\Database\Eloquent\Collection
将被使用。
并且values()
显然返回了支持集合,而不是一个雄辩的集合。
推荐阅读
- c# - 将年份转换为十年的公式
- blockchain - 使用 Infura 提供程序时,web3.eth.getAccounts() 返回空数组。为什么?
- java - 将多个文本视图添加到水平线性布局
- java - 使用 CompletableFuture 避免使用“阻塞”等待
- javascript - 将javascript转换为python
- javascript - Drive API V3:使用 Google Apps 脚本进行多块可恢复上传时文件大小错误(缺少 2 个字节)
- c++ - C++ - 构造函数被用于同一个类两次
- .net - 日历图标和文本字段之间的引导日期时间选择器间隙
- php - PHP从api按星期几对课程列表进行排序
- laravel - 无法让 Xdebug 工作