Отношение HasManyThrough
предполагает отношения от go до 2 hasMany
, однако, глядя на определение вашей таблицы, первое отношение - hasMany
, а второе - belongsTo
. Поскольку оба ключа относятся к одной строке в другой таблице (обе belongsTo
), вместо этого мы можем вместо этого создать отношение belongsToMany
и рассматривать таблицу downloads
как сводную.
Вы можете go об этом по-разному.
Во-первых, я бы предложил установить отношения между Buyer
и Product
(если вы этого еще не сделали):
Продукт
public function buyers()
{
return $this->belongsToMany(Buyer::class, 'downloads')->withTimestamps();
}
Покупатель
public function products()
{
return $this->belongsToMany(Product::class, 'downloads')->withTimestamps();
}
Тогда в вашем методе контроллера вы можете оставить тот же запрос и используйте whereHas () :
public function buyerproducts()
{
$user = auth()->guard('buyer')->user();
if ($user) {
$files = Product::where('deleted', 0)
->whereHas('buyers', function ($query) use ($user) {
$query->where('buyers.id', $user->id);
})
->with('files', 'province:id,name', 'city:id,name')
->get();
// and here I got a loop.. to add some extra data
return response()->json(['data' => $files], 200);
}
return response()->json(['success' => 'no content'], 204);
}
или в качестве альтернативы, вы не можете просто запросить товар прямо у $user
(покупатель):
public function buyerproducts()
{
$user = auth()->guard('buyer')->user();
if ($user) {
$files = $user->products()->where('deleted', 0)
->whereHas('buyers', function ($query) use ($user) {
$query->where('buyers.id', $user->id);
})
->with('files', 'province:id,name', 'city:id,name')
->get();
// and here I got a loop.. to add some extra data
return response()->json(['data' => $files], 200);
}
return response()->json(['success' => 'no content'], 204);
}