Home  >  Q&A  >  body text

Laravel HasManyThrough or BelongsToMany didn't work in my case. Is it a database structure problem?

<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粉505450505P粉505450505433 days ago459

reply all(1)I'll reply

  • P粉970736384

    P粉9707363842023-09-06 00:59:30

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

    reply
    0
  • Cancelreply