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
514
<p>I have 3 tables: </p> <pre class="brush:php;toolbar:false;">products table -id - title - etc.</pre> <pre class="brush:php;toolbar:false;">purchases table -id -code - etc.</pre> <pre class="brush:php;toolbar:false;">purchase_products table -id - purchase_id - product_id -qty - etc.</pre> <p>My goal is to retrieve purchases of a single product. The following relationship doesn't work for me. Tried different approaches using <code>belongsToMany</code> also doesn't work. </p> <pre class="brush:php;toolbar:false;">$this->hasManyThrough( Purchase::class, PurchaseProduct::class, 'purchase_id', 'product_id', 'id', 'id' );</pre> <p>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>
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