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

CGStanton's avatar

Relationship Through Existing Pivot Table

Hi All,

I am working on my most complex project to date, which is probably not that complex to some of you. I am going to try and simplify it for this question.

I have 3 tables with models, and 2 pivot table.

table1 (Model) id, column_a, column_b, created_at, updated_at

table2 (Model) id, column_a, column_b, column_c

table3 (Model) id, column_a

table1_table2 (Pivot) table1_id, table2_id, table3_id, column_a, column_b, column_c...

table1_table3 (Pivot) table1_id, table3_id, column_a, column_b, column_c...

What I am struggling with, is defining the relationship of table2 hasOne table3. Is there anyway to do this?

There is a reason behind why my tables are laid out this way, if it will help solve the problem I can explain it, I just didn't want to clog up this post.

I apologies if this has been asked before; I tried reading through a large amount of pivot table relationship issues, but couldn't find this situation being discussed.

Thanks in advance, Chris

0 likes
2 replies
andonovn's avatar

No, there is no such relationship. You may try to implement the needed joins in the so called scope methods but I believe that's the best you can do for this case.

Also, I am curious, what's the exact use-case for this database design? Maybe if you share the real table names we may suggest a different approach which may end up be more friendly to Eloquent.

CGStanton's avatar

Hi @andonovn,

Thanks for getting back to me.

I'm building an App for monitoring backlinks. I will do my best to explain why I have chosen to create the database structure the way it is.

A domain has many backlinks. A backlink has one anchor text. Many backlinks may share the same anchor text. A domain also has many anchor texts. Many domains may share the same anchor text.

The relationship between a backlink and a domain is unique, and contains a lot of information. The same applies to the relationship between an anchor and a domain.

So my tables look like this:

domains id, domain, created_at, updated_at

backlinks id, url

anchors id, text

backlink_domain backlink_id, domain_id, anchor_id, target_url, link_type...

anchor_domain anchor_id, domain_id, referring_domains, total_links...

I have many other tables, but they all work as I want them to so have not included them here.

Many thanks, Chris

Please or to participate in this conversation.