Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skinnyvin's avatar

Related Products Relationship Issue

I would like to something that I am sure is very simple - but I can't figure it out.

I have a 'products' table and a 'related_products' table.

products
-------------
id
name
desc

related_products
------------------------
product_id
related_product_id

The idea is simple - any given product can have any number of related products.

eg:

Product | Related Product
--------------------------------------
1                |   2
1                |   3
2               |   1
2               |   3

The trouble is I can't figure what the relations should be so that I can pull them.

At the moment:

Product Model

    public function relatedProducts()
    {
        return $this->hasMany(RelatedProduct::class,'product_id');
    }

I would like to be able to do this (but it only returns the related_product_id (but this makes sense as it is not a pivot):

@foreach ($product->relatedProducts as $product)

    {{ $product->name }}
@endforeach 

Ta

0 likes
5 replies
shez1983's avatar

belongsToMany(); is what you need (Many to Many thru pivot table, example in docs if you need)

1 like
skinnyvin's avatar

Thx, seems to be expecting an 'id' field, I must be missing something.

sendderek's avatar

Nice to see somebody else using the exact same solution. I've noticed a downside to this though. Every time you add a related product, you have to manually add the inverse. For example:

Set Product-Z related to Product-A

Get Product-A related to:  none

We see that that Product-A is not related to Product-Z, but Product-Z is related to Product-A. That doesn't make sense. So, now you need to manually add the inverse.

Set Product-A related to Product-Z

Get Product-A, related to: Product-Z

Any suggestions? I'm hoping you may have come across this yourself.

By the way, this is what the relationship looks like in the Product model:

    public function related_products()
    {
        return $this->belongsToMany('App\Product', 'related_products', 'product_id', 'related_product_id');
    }
shez1983's avatar

i think you can do an EVENT created/deleted to do this.. otherwise you wont be able to create a nice relationship (you will have to create your own custom relationship but whih is just a Function to return related products)

Please or to participate in this conversation.