传递给App \ Http \ Controllers \ ApiController :: showAll()的参数1必须是Illuminate \ Database \ Eloquent \ Collection的实例

时间:2019-10-08 21:47:09

标签: laravel collections eloquent

我想检索特定销售商的所有买家。当我删除采摘和其他方法时,在get方法链接后,它就起作用了。但这不是我想要的确切的东西。我该如何解决这个问题?

database structure

<?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);
    }

}

3 个答案:

答案 0 :(得分:1)

您在顶部缺少导入内容:

use Illuminate\Support\Collection;

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

values()显然会返回支持集合,而不是雄辩的。

答案 1 :(得分:0)

如果您的关系从testBuyer,则可以从另一个方向着手寻找买家。您还需要确保从TransactionProduct之间存在一种关系(确保您具有每种关系设置的逆函数)

Seller

您最终将得到一个雄辩的买方集合,他们的交易包括来自特定卖方的产品。

答案 2 :(得分:0)

您应将use Illuminate\Support\Collection;放在apiResponser.php上的文件夹特征中