Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse relationship warning - ask for practices on using inverse relationship

I have the Order table which contains information about a specific order, (when does it start, how many people, etc...) and that Order table has To-Many relationship to Menu Item table. I call that relationship "orderItems".

The compiler gives me warning, "Order.orderedItems -- to-many relationship does not have an inverse: this is an advanced setting (no object can be in multiple destinations for a specific relationship)"

How do you normally do for inverse relationship? Do I need to create a new relationship on the Menu Item to point back to Order, and set the inverse relationship to the "orderedItems"? (In fact, there is no reason for me to save that data in the Menu Item table)

Someone can explain to me why, or at least, point me the reason on why I need to create the inverse relationship on the Menu Item table.

Thanks in advance,

like image 279
Hoang Pham Avatar asked Nov 29 '22 06:11

Hoang Pham


1 Answers

I ran into this warning and problem too! Here's what you need to know...

Lets say you have two tables - Cars and Drivers. You define a one-to-one relationship - one car to one driver, but no inverse.

So now, if you create a car and assign it a driver, if you delete the driver later, and then try and access car.driver, your program will crash. Car.driver will not be nil - it will crash your program.

So, if you don't create an inverse, you can't ever check to see if something is nil, and you can't even safely work with car.driver at all if driver has been deleted.

I don't like how XCode has this set up. It should default to inverse and be a pain in the ass to change it.

Setting up an inverse is simple. Just open your xcdatamodel in XCode, click the existing relationship, and check the inverse box.

like image 168
Andrew Johnson Avatar answered Dec 24 '22 18:12

Andrew Johnson