【发布时间】:2020-02-06 05:17:46
【问题描述】:
我想检索特定卖家的所有买家。当我删除 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);
}
}
【问题讨论】:
-
Laravel 6.0 版
-
你能展示你的模型的关系方法吗?
-
@ShahadatHossain 编辑您的问题并将代码放在那里,而不是在评论中!
-
看看下面的答案怎么样?
标签: laravel collections eloquent