php - Laravel HasManyThrough nor BelongsToMany doesn't work in my case. Is it database structure problem?
I have 3 tables of:
products table
- id
- title
- etc.
purchases table
- id
- code
- etc.
purchase_products table
- id
- purchase_id
- product_id
- qty
- etc.
My goal is to retrieve purchases for a single product. The following relationship doesn't work for me. Tried different ways with belongsToMany
, not working either.
$this->hasManyThrough(
Purchase::class,
PurchaseProduct::class,
'purchase_id',
'product_id',
'id',
'id'
);
In a simple way I could fetch all purchase products by product_id and then retrieve purchases, however I need a relationship for this to work, because of Laravel nova as I want to display purchases on a resource.
Answer
Solution:
Product Model
class Product {
public function purchases()
{
return $this->belongsToMany(Purchase::class, 'purchase_products', 'product_id', 'purchase_id');
}
}
Purchase Model
class Purchase {
public function products()
{
return $this->belongsToMany(Product::class, 'purchase_products', 'purchase_id', 'product_id');
}
}
Source