Do ORMs normally allow circular relations? If so, how would they handle it?
Posted
by SeanJA
on Stack Overflow
See other posts from Stack Overflow
or by SeanJA
Published on 2010-04-22T03:58:29Z
Indexed on
2010/04/22
4:03 UTC
Read the original article
Hit count: 255
I was hacking around trying to make a basic orm that has support for the one => one
and one => many
relationships. I think I succeeded somewhat, but I am curious about how to handle circular relationships.
Say you had something like this:
user::hasOne('car');
car::hasMany('wheels');
car::property('type');
wheel::hasOne('car');
You could then do this (theoretically):
$u = new user();
echo $u->car->wheels[0]->car->wheels[1]->car->wheels[2]->car->wheels[3]->type;
#=> "monster truck"
Now, I am not sure why you would want to do this. It seems like it wastes a whole pile of memory and time just to get to something that could have been done in a much shorter way. In my small ORM, I now have 4 copies of the wheel class, and 4 copies of the car class in memory, which causes a problem if I update one of them and save it back to the database, the rest get out of date, and could overwrite the changes that were already made.
How do other ORMs handle circular references? Do they even allow it? Do they go back up the tree and create a pointer to one of the parents? DO they let the coder shoot themselves in the foot if they are silly enough to go around in circles?
© Stack Overflow or respective owner