1

I am so confused right now in creating a custom table within Drupal 7. My db schema builds a table with three fields one of which is a uid field. I don't have much experience with databases and I was confused as to how to match, relationally, the uid field of my table with the users->uid field. I am told that the foreign key operation within the D7 appear to do this but that they are only there as documentation, the foreign key operation doesn't actually do anything. Is there a way, within the D7 schema, to link two table row items such as uid -- if so how?

2
  • 1
    What should be the effect of that link?
    – Oswald
    Feb 13, 2012 at 0:07
  • The idea behind the link with the user->uid to custom table->uid is that the values in the custom table->uid are auto populated via the user table. Does that make sense? Feb 13, 2012 at 2:05

1 Answer 1

1

Due to mostly historical but also database portability reasons does Drupal currently not use foreign keys.

That however doesn't stop you in any way to relate to other tables. All you need to do is insert the user id into your table and then to a JOIN to the users table if you want to query it. Or do a user_load_multiple() on the uid's separately. If you have a large amount of data, that might actually be better for performance (The default node list in Drupal does that because a LEFT JOIN can get very slow if you have millions of nodes).

You would have to do this in any way, foreign keys don't do this automatically. They do validate your data (e.g. you can't insert a non-existing uid) and you can define how to act when users are deleted (either prevent delete or delete the referenced records too, basically). In the case of users, this wouldn't help you anyway, due to the advanced and configurable User cancellation that Drupal does (e.g. you can configure it to re-assign all public data like comments to the anonymous user).

2
  • Thank you so much. I can't say I can fully understand your answer but I will look into the JOIN function and how foreign keys validate. For now I created a seperate row in my table that deposits the current user->uid, which works for now but in the future for performance I would like to have that already populated so all that needs to be written is my custom rows. Thanks for your help! Feb 21, 2012 at 15:07
  • Not sure what you mean, you will always need to add a uid column to your table and store the uid there yourself.
    – Berdir
    Feb 21, 2012 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.