Home > Net >  Laravel HasManyThrough nor BelongsToMany doesn't work in my case. Is it database structure prob
Laravel HasManyThrough nor BelongsToMany doesn't work in my case. Is it database structure prob

Time:11-16

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.

CodePudding user response:

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');
    }
}
  • Related