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

Omido's avatar
Level 2

Question about relationships

Hello guys,

I'm trying to get better in relationships but right now I'm struggling pretty hard.

So basically I have three tables builds, components and units. And I want to link them together so I need to use a pivot table I guess.

So I have my three models + pivot table. The pivot table has only the ids of builds, components, units and an amount. Then I have to put the three in the pivot table model with a hasMany. And In each of the three, I have to add the pivot table with belongsTo. But I always get null even though I have the right id's in the pivot table.

Would be really nice of you guys, if you could explain to me what im doing wrong. Because right now im pretty stuck.

Kind regards Omidoo :)

0 likes
4 replies
Tray2's avatar

It's a bit har to understand the relationship between the tables from your description.

However this is a little trick that I use to be able to know what I need in my database model.

Lets say I have a books table.

  • A book has an author + An author can have many books = One to many
  • A book has one format + A format can have many books = One to many

Now to make it a bit more complex (pivot)

  • A book can have many authors + An author can have many books = Many to many.

So I suggest you do that with your three tables

  • A build can have ??? A ??? can have ? builds and so on.
1 like
Omido's avatar
Level 2

Hey, thanks for your response. I'm sorry for my bad explanation, I can give you another one.

I'm struggling to understand the complete concept behind that.

So let's say I Recipe book, which consists of three tables Recipes, Ingredients & Units.

Now I hook them up together so I know which combination of Ingredient & Unit belongs to the given Recipe.

So I thought I have to do some kind of Pivot Table where I have the id from the Recipe, the Ingredient, and the Unit in there. Additionally, I add another column in there for the Amount which is just a basic integer.

So I can access all the Ingredients with the correct Unit and Amount directly from the Recipe trough the Pivot table.

Snapey's avatar
Snapey
Best Answer
Level 122

in this specific case, I would have just ingredients and recipe.

recipe has many ingredients, ingredient belongs to recipe.

ingredient contains its name, the quantity and measure . things like cup, spoon, ml, gram etc can come from simple lookup list.

So no pivot in this example?

2 likes
Omido's avatar
Level 2

Yea I thought about this as well, but I thought it would become very fast very redundant.

But I think I'm going the way you described.

Thank you very much.

Please or to participate in this conversation.