Laravel HasManyThrough or BelongsToMany didn't work in my case. Is it a database structure problem?
P粉505450505
P粉505450505 2023-09-05 09:33:50
0
1
361

I have 3 tables:

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 of a single product. The following relationship doesn't work for me. Tried different approaches using belongsToMany also doesn't work.

$this->hasManyThrough( Purchase::class, PurchaseProduct::class, 'purchase_id', 'product_id', 'id', 'id' );

In a simple way I can get all the purchased products by product_id and then retrieve the purchased items but I need a relationship to make it work in Laravel nova as I want to display the purchased items on the resource .

P粉505450505
P粉505450505

reply all (1)
P粉970736384

Product number

class Product { public function purchases() { return $this->belongsToMany(Purchase::class, 'purchase_products', 'product_id', 'purchase_id'); } }

Purchase Mode

class Purchase { public function products() { return $this->belongsToMany(Product::class, 'purchase_products', 'purchase_id', 'product_id'); } }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!