首页 > 解决方案 > 传递给 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);
    }

}

标签: laravelcollectionseloquent

解决方案


您在顶部缺少导入:

use Illuminate\Support\Collection;

否则它假定Illuminate\Database\Eloquent\Collection将被使用。

并且values()显然返回了支持集合,而不是一个雄辩的集合。


推荐阅读